首页 > 解决方案 > 在 Python 中按多个条件对数据进行分组

问题描述

我想我有一个快速的问题,但我没有找到用简单的话谷歌搜索它的方法。

我有一个像这样的原始数据集:

 Number of account     Value
      123               100
      456               300
      789               400
      910               100
      674               250

我有一个方法表可以将这些原始数据整合成有用的东西。看起来像:

 Variable              Number of account
    "a"                  123, 456, 910
    "b"                    789,674

所以,最后我想得到一张这样的桌子:

 Variable              Number of account
    "a"                  Sum of values for(123, 456, 910)
    "b"                  Sum of values for(789,674)

我最初的想法是做类似的事情:对于方法表中的每一行,对于方法表中的每个帐户数,原始数据中的总和值

两个问题:

  1. 巩固它的最佳方法是什么?
  2. 如果方法表中的账户数是逗号分隔的字符串怎么办?(“123,456,910”)。我可以在 pandas DataFrame 的一个单元格中存储多个数字吗

标签: pythonpandasgroupingconsolidation

解决方案


假设我在两个数据框中有数据:

df是 :

Number_of_account     Value
      123               100
      456               300
      789               400
      910               100
      674               250

并且table_2是:

Variable              Number_of_account
    "a"                  123,456,910
    "b"                    789,674

首先,我将从 table2 创建一个查找表:

lookup_table = pd.concat([pd.Series(row['Variable'], row['Number_of_account'].split(','))              
                         for _, row in table_2.iterrows()]).reset_index()
lookup_table.columns = ["Number_of_account", "variable"]
lookup_table.Number_of_account = pd.to_numeric(lookup_table.Number_of_account)

结果是:

   Number_of_account variable
0                123        a
1                456        a
2                910        a
3                789        b
4                674        b

然后,我将主数据框 ( df) 与查找表合并,并用于groupby计算值的总和。

df = pd.merge(df, lookup_table, on="Number_of_account")
df.groupby("variable")["Value"].sum()

结果是:

variable
a    500
b    650

推荐阅读