我有一个生成的数据帧,代码如下:
# 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]
我想以最优化的方式进行优化,因为运行时间对我来说是个问题。所以要避免循环。有人能告诉我如何实现这一最优化的方法吗
最通用的解决方案是将所有值转换为字符串,使用
join
和lastreplace
:如果只需要筛选某些列:
或单独处理每一列-如有必要
replace
,并将数字列转换为字符串:或者在转换为字符串后,添加
_
,sum
,但在将删除跟踪_
替换为rstrip
后需要:相关问题 更多 >
编程相关推荐