python f'string 在 pd.Series.map 函数中不起作用

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

我有一个pd系列,

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

当我这样做时,

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   

如何使用格式化字符串获得相同的结果?

s.map(f'this is a string {?}') ?

使用 lambda 函数 {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

没有 map / apply + lambda 的解决方案是可能的。您可以将列表直接分配给系列。列表理解通常更有效,因为 pd.Series.apply 未向量化:

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