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 {?}') ?
0

2 Answers 2

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
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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.