如何在字符串格式化中使用dataframe列

2024-04-27 23:46:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我不知道怎么问。要使用格式化将行值添加到字符串中。如果我有如下类似的df:

^{tb1}$

我希望输出如下所示:

^{tb2}$

我正在使用df['string'] = f'{df['qty']} {df['things']} on the {df['place']}',但没有得到确切的答案


Tags: the字符串答案dfstringonplaceqty
3条回答

你可以在这里使用^{}

df["qty"].astype(str).str.cat(
    [df["things"], ("on the " + df["place"])], sep=" "
)

0    1 Apple on the Table
1    4 Mango on the Chair
2     3 Coke on the Floor
3      2 Pen on the Table
Name: qty, dtype: object

如果您想使用f-string,那么可以在轴1上使用df.apply(但是这种方法很慢,应该作为最后手段使用)

df.apply(lambda x: f'{x.qty} {x.things} on the {x.place}', axis=1)
  1. 将数据帧转换为字典

  2. 以相同的格式将新数据列添加到字典中

  3. 将字典转换回数据帧

    data_dict=df.to_dict()

    数据记录[“字符串”]=“桌上有一个苹果”…]

    来自dict的pd.数据帧(数据dict)

这里有一篇文章可能会有所帮助:https://re-thought.com/how-to-add-new-columns-in-a-dataframe-in-pandas/

只需使用:-

df['string']=df['qty'].astype(str)+' '+df['things']+' on the '+df['place']

相关问题 更多 >