python - 为什么 f-strings 格式不适用于 Pandas DataFrames?

标签 python python-3.x pandas dataframe f-string

给定一个带有 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/

相关文章:

python - 如何在Hadoop流中使用opt解析器作为映射器指定python脚本

python - 如何诊断似乎什么都不做的 Django 注册表?

python-3.x - 在python中使用 key 加密消息

python - 如何从 pandas read_html 读取并平坦/规范化一系列表?

python - 具有单表继承删除错误的 SQLAlchemy

python - Matplotlib:如何使网格的替代垂直线虚线?

python - 如何删除 python pandas read_csv 中没有标题的列

python - 如何在模型中引发 HTTP 400?

python - 计算网络中所有可能配对的连接总和

pandas - 如何将年、日、月转换为日期时间?