Skip to main content
 首页 » 编程设计

python之Pandas之如何根据各种条件在多列上执行 'group by'

2025年05月04日13cmt

我坚持使用各种条件对多个列进行分组:

我的数据框是这样的:

code    product brand   lvl1    lvl2    lvl3     lvl4   lvl5        price 
8968653 ABC             Milk    Mother  Toddler         Porridge    69 
8968653 ABC     AB              Baby                    Bayi        95 

代码和产品名称是公共(public)字段。 所有其他列应根据以下条件分组:

  1. 两个单元格都是空的:显示 NaN

  2. 一个单元格为空:显示其他值

  3. 两个单元格都是非空的:通过管道合并单元格

  4. 价格列应显示平均值

预期输出:

code    product brand   lvl1 lvl2        lvl3     lvl4  lvl5         price 
8968653 ABC     AB      Milk Mother|Baby Toddler  NaN   Porridge|Bayi    82 

请您参考如下方法:

我们可以分几步完成:

  1. 首先我们得到一个列的列表,这些列是string类型和numeric
  2. 其次我们使用 groupby.agg 或 groupby.mean 取决于我们是否有 string 列或 numeric 列:
  3. 我们清理我们的数据框,其中有不必要的 |。
# Step 1 get string and numeric columns 
str_cols = df.iloc[:, 2:-1].columns 
num_cols = df.iloc[:, -1:].columns 
 
# Step 2 groupby on string and numeric columns 
d1 = df.groupby(['code','product'])[str_cols].agg('|'.join) 
d2 = df.groupby(['code', 'product'])[num_cols].mean() 
 
# Join the dataframe back as 1 
df = d1.join(d2).reset_index() 

输出 1:

      code product brand   lvl1         lvl2      lvl3 lvl4           lvl5  price 
0  8968653     ABC   |AB  Milk|  Mother|Baby  Toddler|    |  Porridge|Bayi     82 

现在我们通过删除管道 | 来清理数据框。

df = df.replace('(^\||\b\|\b|\|$)', '', regex=True) 

最终输出

      code product brand  lvl1         lvl2     lvl3 lvl4           lvl5  price 
0  8968653     ABC    AB  Milk  Mother|Baby  Toddler       Porridge|Bayi     82