8

I have a pd series,

s = pd.Series([1, 2, 3, np.nan])

when I do,

s.map('this is a string {}'.format)
[out]
0    this is a string 1.0
1    this is a string 2.0
2    this is a string 3.0
3    this is a string nan   

how can I get the same result by using formatted string?

s.map(f'this is a string {?}') ?
jpp
  • 159,742
  • 34
  • 281
  • 339
Pyd
  • 6,017
  • 18
  • 52
  • 109

2 Answers2

5

Use lambda function with {x}:

print (s.map(lambda x: f'this is a string {x}'))
#alternative with different value
#print (s.map(lambda val: f'this is a string {val}'))
0    this is a string 1.0
1    this is a string 2.0
2    this is a string 3.0
3    this is a string nan
dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
4

A solution is possible without map / apply + lambda. You can assign a list directly to a series. A list comprehension is often more efficient since pd.Series.apply is not vectorised:

df = pd.DataFrame({'s': pd.Series([1, 2, 3, np.nan])})

df['t'] = [f'this is a string {i}' for i in df['s']]

print(df)

     s                     t
0  1.0  this is a string 1.0
1  2.0  this is a string 2.0
2  3.0  this is a string 3.0
3  NaN  this is a string nan
jpp
  • 159,742
  • 34
  • 281
  • 339