为什么Pandas不支持f-string格式化?

18
给定一个包含“产品编号”和“数量”的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

我想根据“金额”添加一个“描述”列,预计会是这个样子:
  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格式化进行字符串拼接吗?

我真的很希望这也能够正常工作。非常令人烦恼。 - mike01010
2个回答

21
你需要逐个值进行迭代,例如通过apply进行迭代:
df['Description'] = df["Amount"].apply(lambda x: f'Amount is {x}')

或者使用列表推导式:

df['Description'] = [f'Amount is {x}' for x in df["Amount"]]

print (df)

  Product Id   Amount        Description
0     504145  12000.0  Amount is 12000.0
1     555933  23010.5  Amount is 23010.5

你的解决方案:

df['Description'] = f'Amount is {df["Amount"].astype(str)}'

working different - 它将Series的每个值(包括索引)附加到字符串中,并重复为新列的所有值。


1
谢谢,如果要连接更多的列怎么办?例如:f'产品ID为{df["Product Id"]}的金额为{df["Amount"].astype(str)}' - henrywongkk
4
然后使用 df['Description'] = df.apply(lambda x: f'产品编号为{x["Product Id"]}的金额为{x["Amount"]}', axis=1) - jezrael
4
@henrywongkk - 或 df['Description'] = [f'产品 {a} 的金额为 {b}' for a, b in zip(df["Product Id"], df["Amount"])] - jezrael

3

另一个选项是使用aggformat

df['description'] = df.agg('Amount is {0[Amount]}'.format, axis=1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接