透视并重命名 Pandas 数据框 [英] Pivot and rename Pandas dataframe
本文介绍了透视并重命名 Pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式的数据框
Date Datediff Cumulative_sum
01 January 2019 1 5
02 January 2019 1 7
02 January 2019 2 15
01 January 2019 2 8
01 January 2019 3 13
我想从数据框中旋转列 Datediff 使最终结果看起来像
and I want to pivot the column Datediff from the dataframe such that the end result looks like
Index Day-1 Day-2 Day-3
01 January 2019 5 8 13
02 January 2019 7 15
我使用了 pivot 命令 shuch
I have used the pivot command shuch that
pt = pd.pivot_table(df, index = "Date",
columns = "Datediff",
values = "Cumulative_sum") \
.reset_index() \
.set_index("Date"))
返回透视表
1 2 3
01 January 2019 5 8 13
02 January 2019 7 15
然后我可以使用循环重命名重命名列
And I can then rename rename the columns using the loop
for column in pt:
pt.rename(columns = {column : "Day-" + str(column)}, inplace = True)
返回的正是我想要的.但是,我想知道是否有更快的方法在旋转时重命名列并完全摆脱循环.
which returns exactly what I want. However, I was wondering if there is a faster way to rename the columns when pivoting and get rid of the loop altogether.
推荐答案
df.add_prefix('Day-')
在您的解决方案中:
pt = (pd.pivot_table(df, index = "Date",
columns = "Datediff",
values = "Cumulative_sum")
.add_prefix('Day-'))
这篇关于透视并重命名 Pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文