上一篇文章讲解了pandas的数据透视表:piovt_table,网友留言说,处理完数据后,格式不是想要的那种,要用于报告的话还是不行。
这篇文章篇幅不长,主要讲解一下如何处理透视后的格式问题:
首先导入需要处理的数据:
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar"],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two"],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large"],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
"E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
df
数据透视:应用一个函数的情况:
table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
aggfunc=np.mean)
table
直接重置索引就可以去除掉之前的多级索引
table.reset_index()
如果觉得格式还不行可以修改列名:
table2=table.reset_index()
table2.columns=["A","B","C_平均值","D_平均值"]
table2
如果你用的是多个函数,那就稍微麻烦点,但是还是有办法的,
table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'],
aggfunc={'D': np.mean,
'E': [min, max, np.mean]})
table
这样处理的格式复制到excel:
这显然不是我们想要的,我们需要的是一个行索引,一个列索引就够了
方法1:直接删除掉多余的索引
table2 = table.copy(deep=True)
table2.columns = table2.columns.droplevel(0)
table2
接下来处理行索引:
table2.reset_index()
这基本上就是我们想要的了,但是行标签还需要改一下:
table2.columns=["A","C","D_mean","D_max","E_mean","E_max"]
table2
方法2、
直接将索引合并
table2 = table.copy(deep=True)
table2.columns = ["_".join(x) for x in table2.columns.ravel()]
table2
table2.reset_index()
这样的结果和方法1是一样的了
还有一种特殊的处理方法,直接降维:
tabel2=table.stack().reset_index()
tabel2.columns=["A","C","方法","D","E"]
tabel2
如果这篇文章对你很有帮助,点个赞,关注一下,么!
閱讀更多 嘩啦圈的夢 的文章