2024-04-27 23:46:03 发布
网友
我不知道怎么问。要使用格式化将行值添加到字符串中。如果我有如下类似的df:
我希望输出如下所示:
我正在使用df['string'] = f'{df['qty']} {df['things']} on the {df['place']}',但没有得到确切的答案
df['string'] = f'{df['qty']} {df['things']} on the {df['place']}'
你可以在这里使用^{}
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(但是这种方法很慢,应该作为最后手段使用)
f-string
df.apply
df.apply(lambda x: f'{x.qty} {x.things} on the {x.place}', axis=1)
将数据帧转换为字典
以相同的格式将新数据列添加到字典中
将字典转换回数据帧
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']
你可以在这里使用^{}
如果您想使用
f-string
,那么可以在轴1上使用df.apply
(但是这种方法很慢,应该作为最后手段使用)将数据帧转换为字典
以相同的格式将新数据列添加到字典中
将字典转换回数据帧
data_dict=df.to_dict()
数据记录[“字符串”]=“桌上有一个苹果”…]
来自dict的pd.数据帧(数据dict)
这里有一篇文章可能会有所帮助:https://re-thought.com/how-to-add-new-columns-in-a-dataframe-in-pandas/
只需使用:-
相关问题 更多 >
编程相关推荐