python中Dataframe的Concat列?

2024-09-21 05:47:45 发布

您现在位置: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) 

我希望生成一个列表,将所有三列合并在一起,并通过“u”删除空格,同时删除所有尾随空格:-

[A_Music_Theater_10000, B_Poetry_Music_5000,C_Theatre_Comedy_15000,D_Comedy_Theatre_2000]

我想以最优化的方式进行优化,因为运行时间对我来说是个问题。所以要避免循环。有人能告诉我如何实现这一最优化的方法吗


Tags: the数据代码dataframepandasdfpoetryas
1条回答
网友
1楼 · 发布于 2024-09-21 05:47:45

最通用的解决方案是将所有值转换为字符串,使用join和lastreplace

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,但在将删除跟踪_替换为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

相关问题 更多 >

    热门问题