给定一个带有 Product Id
的 DataFrame和 Amount
:
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-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 字符串格式?或者不建议在 Pandas 中使用 f-strings 格式进行字符串连接?
最佳答案
您需要按每个值进行迭代,例如来自 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)}'
工作方式不同 - 它将系列的每个值(也带有索引)附加到字符串,并像常量一样为新列的所有值重复。
关于python - 为什么 f-strings 格式不适用于 Pandas DataFrames?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602169/