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 {?}') ?
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With