![](/img/trans.png)
[英]Group by dataframe in python and concat strings on multiple columns
[英]Concat Columns of Dataframe in python?
我有一个使用以下代码生成的数据框:
# importing pandas as pd
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'Category':['A', 'B', 'C', 'D'],
'Event':['Music Theater', 'Poetry Music', 'Theatre Comedy', 'Comedy Theatre'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)
我希望生成一个组合所有三列的列表,并通过“_”删除空格,并删除所有尾随空格:-
[A_Music_Theater_10000, B_Poetry_Music_5000,C_Theatre_Comedy_15000,D_Comedy_Theatre_2000]
我想以最优化的方式来处理它,因为运行时间对我来说是个问题。 所以要避免 for 循环。 谁能告诉我如何实现这是最优化的方式?
最通用的解决方案是将所有值转换为字符串,使用join
和 last replace
:
df['new'] = df.astype(str).apply('_'.join, axis=1).str.replace(' ', '_')
如果只需要过滤一些列:
cols = ['Category','Event','Cost']
df['new'] = df[cols].astype(str).apply('_'.join, axis=1).str.replace(' ', '_')
或单独处理每一列 - 如有必要,将数字列replace
并转换为字符串:
df['new'] = (df['Category'] + '_' +
df['Event'].str.replace(' ', '_') + '_' +
df['Cost'].astype(str))
或者在转换为字符串后添加_
、 sum
,但在将删除 traling _
替换为rstrip
后是必需的:
df['new'] = df.astype(str).add('_').sum(axis=1).str.replace(' ', '_').str.rstrip('_')
print(df)
Category Event Cost new
0 A Music Theater 10000 A_Music_Theater_10000
1 B Poetry Music 5000 B_Poetry_Music_5000
2 C Theatre Comedy 15000 C_Theatre_Comedy_15000
3 D Comedy Theatre 2000 D_Comedy_Theatre_2000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.