给定一个包含“产品编号”和“数量”的DataFrame:
我想根据“金额”添加一个“描述”列,预计会是这个样子:
当我使用f-strings格式化时,结果是将整个列
然而,使用简单的字符串拼接(+)也能正常工作。
为什么在Pandas DataFrame中使用f-strings格式化会出现这种行为?我应该如何修复它以使用f-strings格式化?或者在Pandas中不建议使用f-strings格式化进行字符串拼接吗?
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
我想根据“金额”添加一个“描述”列,预计会是这个样子:
Product Id Amount Description
0 504145 12000.0 Amount is 12000.0
1 555933 23010.5 Amount is 23010.5
当我使用f-strings格式化时,结果是将整个列
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-strings格式化会出现这种行为?我应该如何修复它以使用f-strings格式化?或者在Pandas中不建议使用f-strings格式化进行字符串拼接吗?