重命名数据透视表中的列 [英] Renaming Columns from pivot_table
问题描述
我在数据帧上运行pivot_table
,结果列名称为:
I run a pivot_table
on a dataframe and the resulting column names are:
('firstvar', 8001) ('firstvar', 8002) ('secondvar', 8001) ('secondvar', 8002)
但是在使用数据之前,我需要将这些列重命名为以下几行:
But before I can use the data I need to rename the columns to something along these lines:
firstvar_8001 firstvar_8002 secondvar_8001 secondvar_8002
我尝试查看是否可以在执行数据透视表时完成此操作,但我认为这不可能. 因此,相反,我正在寻找一种解决方案,以便在将数据帧中的列保存为csv之前重命名
I tried to see if this could be done when doing the pivot table but I don't think it can be. So instead I'm looking for a solution to renaming the columns in the dataframe before I save it as a csv
我需要在可能更改8000代码的多个文件上运行此文件,因此我考虑使用regex
,但找不到使用regex
重命名数据框中的列的任何支持.
I need to run this on multiple files where the 8000 codes might change so I was thinking of using regex
but I can't find any support for renaming columns in a dataframe using regex
.
所以我现在意识到名称实际上是python tuples
,我正在努力将其转换为字符串并立即加入它们.
So I realize now that the names are actually python tuples
and I'm working on converting them to strings and joining them now.
所以我发现了一个笨拙的解决方案.我的问题是不允许我重命名元组,所以我最终只是导出并重新导入以平整级别,然后以这种方式重命名它们.我真的不喜欢这种解决方案,因此,如果有人提出了更好的解决方案的建议,那将是一个好主意.我真的很感激!
So I found a clumsy solution. My issue was that it wouldn't allow me to rename the tuples so I ended up just exporting and re-import to flatten the levels and then renaming them in that fashion. I really don't like the solution though so if anyone has a suggestion for a better way to do it; I would really appreciate it!
推荐答案
最新答案,但可能对其他人有帮助...
Late answer but can be helpful for others...
my_colnames = []
for i, a in enumerate(my_pivoted_table.columns.get_level_values(1)):
my_colnames.append(str(a) + '_' + str(my_pivoted_table.columns.get_level_values(0)[i]))
my_pivoted_table.columns = my_colnames
这篇关于重命名数据透视表中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!