【发布时间】:2020-02-24 09:11:10
【问题描述】:
给定一个带有Product Id 和Amount 的DataFrame:
df = pd.DataFrame([['504145', 12000.0],
['555933', 23010.5]],
columns=['Product Id', 'Amount'])
df
Out[1]:
Product Id Amount
0 504145 12000.0
1 555933 23010.5
我想添加一个基于Amount 的“描述”列,预计如下所示:
Product Id Amount Description
0 504145 12000.0 Amount is 12000.0
1 555933 23010.5 Amount is 23010.5
当我使用 f 字符串格式时,结果是将整列 Amount 聚合为一个系列,而不是使用特定行的值进行字符串连接:
df['Description'] = f'Amount is {df["Amount"].astype(str)}'
df
Out[2]:
Product Id Amount Description
0 504145 12000.0 Amount is 0 12000.0\n1 23010.5\nName: Am...
1 555933 23010.5 Amount is 0 12000.0\n1 23010.5\nName: Am...
但是,使用+ 进行简单的字符串连接可以正常工作:
df['Description'] = "Amount is " + df["Amount"].astype(str)
df
Out[9]:
Product Id Amount Description
0 504145 12000.0 Amount is 12000.0
1 555933 23010.5 Amount is 23010.5
为什么 Pandas DataFrame 中的 f 字符串格式会这样?我应该如何修复它以使用 f-strings 格式?还是不建议在 Pandas 中使用 f-strings 格式进行字符串连接?
【问题讨论】:
标签: python python-3.x pandas dataframe f-string