python - 在 Python 中格式化数据透视表

标签 python sorting pandas format dataframe

我正在尝试根据不同列中的计数重新格式化表格。

df = pd.DataFrame({'Number': [1, 2, 3, 4, 5], 'X' : ['X1', 'X2', 'X3', 'X3', 'X3'], 'Y' : ['Y2','Y1','Y1','Y1', 'Y2'], 'Z' : ['Z3','Z1','Z1','Z2','Z1']})

   Number   X   Y   Z
0       1  X1  Y2  Z3
1       2  X2  Y1  Z1
2       3  X3  Y1  Z1
3       4  X3  Y1  Z2
4       5  X3  Y2  Z1

我希望第一行按频率进行 X 排序(X3 第一个,因为它出现了两次)然后对于每个 X 值,计算其 Y 和 Z 值的频率并打印出现次数最多的那个。

   X3  X2  X1
Y  Y1  Y1  Y2           
Z  Z1  Z1  Z3

到目前为止我有可以排序的代码

import pandas as pd

df = pd.DataFrame({'Number': [1, 2, 3, 4, 5], 'X' : ['X1', 'X2', 'X3', 'X3', 'X3'], 'Y' : ['Y2','Y1','Y1','Y1', 'Y2'], 'Z' : ['Z3','Z1','Z1','Z2','Z1']})
pivot = df.pivot_table(index='X', columns=['Y', 'Z'], values = 'Number', aggfunc='count')
# clean the table from NaNs (not necessary, but more beautiful):
pivot.fillna(0, inplace=True)
pivot['sum'] = pivot.sum(axis=1)
pivot.sort('sum', ascending=False, inplace=True)
df = pivot[:5].transpose()
df.to_csv('sorted.csv')

和输出:

Y   Z   X3  X1  X2
Y1  Z1  1   0   1
Y1  Z2  1   0   0
Y2  Z1  1   0   0
Y2  Z3  0   1   0
sum     3   1   1

但这仍然不是我想要的,谁能帮我解决这个问题?谢谢!

最佳答案

您将需要自定义mode 函数,因为pandas.Series.mode如果至少两次什么都没发生,则不起作用;虽然下面的不是最有效的,但它可以完成工作:

>>> mode = lambda ts: ts.value_counts(sort=True).index[0]
>>> cols = df['X'].value_counts().index
>>> df.groupby('X')[['Y', 'Z']].agg(mode).T.reindex(columns=cols)
   X3  X1  X2
Y  Y1  Y2  Y1
Z  Z1  Z3  Z1

请注意,在您的示例框架中,X1X2 在出现次数上是相关的。

关于python - 在 Python 中格式化数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856187/

相关文章:

python - 从 WSGI 脚本获取 URL

java - 按排序顺序将文件写入目录

oracle - Oracle中的时间戳排序顺序

python - 以相同的顺序一次洗牌两个列表

python - 如何将带有列表值的 pandas 列连接到一个列表中?

python - Pandas One 热编码 : Bundling together less frequent categories

python - cProfile 导入

python - python中的Interceptor如何应用

python - 在seaborn catplot中为每个类别添加从最小点到最大点的水平线

python - 从嵌套列表构造 pandas 数据框