Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python f'string not working in pd.Series.map function

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 {?}') ?
like image 659
Vicky Avatar asked Sep 11 '18 06:09

Vicky


People also ask

Are F strings Pythonic?

When you're formatting strings in Python, you're probably used to using the format() method. But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.

What does F {} mean in Python?

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values.

Can you nest F strings in Python?

Nested F-StringsYou can embed f-strings inside f-strings for tricky formatting problems like adding a dollar sign to a right aligned float, as shown above.

How do I install an F-string in Python?

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.


2 Answers

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
like image 141
jezrael Avatar answered Oct 23 '22 10:10

jezrael


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
like image 28
jpp Avatar answered Oct 23 '22 09:10

jpp