6

我有一个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 {?}') ?
4

2 回答 2

3

使用 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
于 2018-09-11T06:47:26.063 回答
2

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
于 2018-09-29T15:50:05.107 回答