【问题标题】:Pandas: Pivoting multiple tables into single and counting occurencesPandas:将多个表转换为单个表并计算出现次数
【发布时间】:2023-03-25 06:50:02
【问题描述】:

我正在尝试创建一个将多个(超过 8 个)数据框合并为一个的数据透视表。

这些表有多个列,但我会在这里保持简单:

Table1

week        project 
42          ABC
42          FGA
42          ZTR
44          HTZ
44          UZR
44          LOP
46          POL
46          ZTT
46          ART
46          ART
...

在某些几周内可能不会发生任何项目。表 2、3、4 等肯定会有不同的每周出现次数。

所有表中唯一的公共列是周列。一些表有更多一些更少的列,列标题也可能不同。周列是所有列中唯一的通用列,并且我认为在这里单独使用就足够了。

我的目标是计算每周在所有表中出现的次数。最终,我想要实现的是:

index  table1  table2  table3  table4  table5
42       3       3       4       11      23
43       0       4       10      15      7
44       3       12      8       9       1
45       0       7       0       0       8
46       4       6       7       0       22
47       8       3       12      6       0

这样的计数在 excel 中非常容易,只需使用带有计数的数据透视表即可。 我将如何在 Python 中处理这种情况?

【问题讨论】:

  • 使用 concat 创建一个包含所有内容的数据框,并使用 pivot_table 获取结果

标签: python pandas pivot-table


【解决方案1】:

您可以将concatkeys 参数一起使用,然后将groupbyunstack 一起使用。

这里要注意的是你手动推断密钥,如果每个表都有一个id来显示它的来源会更好。

tables = [df1,df2] # if you want to make the keys dynamic, 
#tables = table_dict = dict(zip([f'table {i}' for i in range(1,len(tables) + 1)],tables))

df_new = (
    pd.concat(tables, axis=0, keys=["table1", "table2"])
    .set_index("week", append=True)
    .groupby(level=[0, 2])
    .count()
    .unstack(0)
)

     project       
      table1 table2
week               
42         3      3
44         3      3
46         4      4

【讨论】:

  • 谢谢。但是,发生了一些非常奇怪的事情。我收到一个两级列标题。第一级似乎是表 1 中的所有列(周、项目、所有者、日期),第二级似乎是我想要的数据透视表的重复(数字是正确的,但为 table1 的每一列一遍又一遍地复制) .
  • 嗨@Botan 请提供一个模仿您的输入/输出的样本,我很乐意提供帮助。仅靠猜测工作很难编写解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 2019-11-28
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多