python - 将 pandas 数据框列及其顺序保留在数据透视表中

标签 python pandas dataframe pivot-table

我有一个数据框:

df = pd.DataFrame({'No': [123,123,123,523,523,523,765], 
                  'Type': ['A','B','C','A','C','D','A'],
                  'Task': ['First','Second','First','Second','Third','First','Fifth'],
                  'Color': ['blue','red','blue','black','red','red','red'],
                  'Price': [10,5,1,12,12,12,18],
                  'Unit': ['E','E','E','E','E','E','E'],
                  'Pers.ID': [45,6,6,43,1,9,2]
                  })

所以它看起来像这样:

df
+-----+------+--------+-------+-------+------+---------+
| No  | Type |  Task  | Color | Price | Unit | Pers.ID |
+-----+------+--------+-------+-------+------+---------+
| 123 | A    | First  | blue  |    10 | E    |      45 |
| 123 | B    | Second | red   |     5 | E    |       6 |
| 123 | C    | First  | blue  |     1 | E    |       6 |
| 523 | A    | Second | black |    12 | E    |      43 |
| 523 | C    | Third  | red   |    12 | E    |       1 |
| 523 | D    | First  | red   |    12 | E    |       9 |
| 765 | A    | First  | red   |    18 | E    |       2 |
+-----+------+--------+-------+-------+------+---------+

然后我创建了一个数据透视表:

piv = pd.pivot_table(df, index=['No','Type','Task'])

结果:

                 Pers.ID  Price
No  Type Task                  
123 A    First        45     10
    B    Second        6      5
    C    First         6      1
523 A    Second       43     12
    C    Third         1     12
    D    First         9     12
765 A    Fifth         2     18

如您所见,问题是:

  • 多列消失(颜色和单位)

  • Price 和 Pers.ID 列的顺序与原始数据帧中的顺序不同。

我试图通过执行来解决这个问题:

cols = list(df.columns)
piv = pd.pivot_table(df, index=['No','Type','Task'], values = cols)

但结果是一样的。

我阅读了其他帖子,但没有一个帖子以我可以使用它的方式匹配我的问题。

谢谢!

编辑:所需的输出

                   Color  Price   Unit  Pers.ID
No  Type Task                  
123 A    First      blue     10      E       45
    B    Second      red      5      E        6
    C    First      blue      1      E        6
523 A    Second    black     12      E       43
    C    Third       red     12      E        1
    D    First       red     12      E        9
765 A    Fifth       red     18      E        2

最佳答案

我认为问题出在 pivot_table 默认聚合函数是 mean,所以 strings columns are excluded 。所以需要自定义函数,而且顺序也改变了,所以reindex是必要的:

f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ', '.join(x)
cols = df.columns[~df.columns.isin(['No','Type','Task'])].tolist()

piv = (pd.pivot_table(df, 
                     index=['No','Type','Task'], 
                     values = cols,
                     aggfunc=f).reindex(columns=cols))
print (piv)
                 Color  Price Unit  Pers.ID
No  Type Task                              
123 A    First    blue     10    E       45
    B    Second    red      5    E        6
    C    First    blue      1    E        6
523 A    Second  black     12    E       43
    C    Third     red     12    E        1
    D    First     red     12    E        9
765 A    Fifth     red     18    E        2

另一个具有groupby和相同聚合函数的解决方案,排序不是问题:

df = (df.groupby(['No','Type','Task'])
       .agg(lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else ', '.join(x)))
print (df)
                 Color  Price Unit  Pers.ID
No  Type Task                              
123 A    First    blue     10    E       45
    B    Second    red      5    E        6
    C    First    blue      1    E        6
523 A    Second  black     12    E       43
    C    Third     red     12    E        1
    D    First     red     12    E        9
765 A    Fifth     red     18    E        2

但如果需要仅将前 3 列设置为 MultiIndex:

df = df.set_index(['No','Type','Task'])
print (df)
                 Color  Price Unit  Pers.ID
No  Type Task                              
123 A    First    blue     10    E       45
    B    Second    red      5    E        6
    C    First    blue      1    E        6
523 A    Second  black     12    E       43
    C    Third     red     12    E        1
    D    First     red     12    E        9
765 A    Fifth     red     18    E        2

关于python - 将 pandas 数据框列及其顺序保留在数据透视表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361426/

相关文章:

python - Pandas 改进

python - 查找mp3文件的长度

将字符串连接到 None 的 Pythonic 方法

python - 正确预处理 1D CNN 的 csv 数据

python - 在 Pandas 中,如何复制列中具有特定值的所有行,并更改重复项中的该列值?

python - 如何从值列表中将新列附加到 pandas groupby 对象

python - 从 pandas DataFrame 中的列中减去平均值

python - MySQL 服务器消失了 python MySQLdb

python - 使用 pandas df.query() 过滤列中的字符串值列表

python - 将每日数据重新采样为每小时数据帧并复制内容