【问题标题】:Why doesn't f-strings formatting work for Pandas DataFrames?为什么 f-strings 格式不适用于 Pandas DataFrames?
【发布时间】:2020-02-24 09:11:10
【问题描述】:

给定一个带有Product IdAmount 的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


    【解决方案1】:

    您需要按每个值进行迭代,例如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)}'
    

    工作方式不同 - 它将 Series 的每个值(也带有索引)附加到字符串并像常量一样重复新列的所有值。

    【讨论】:

    • 谢谢,如果有更多的列要连接呢?例如f'Amount for {df["Product Id"]} is {df["Amount"].astype(str)}'
    • @henrywongkk - 然后使用df['Description'] = df.apply(lambda x: f'Amount for {x["Product Id"]} is {x["Amount"]}', axis=1)
    • @henrywongkk - 或df['Description'] = [f'Amount for {a} is {b}' for a, b in zip(df["Product Id"], df["Amount"])]
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多