我坚持使用各种条件对多个列进行分组:
我的数据框是这样的:
code product brand lvl1 lvl2 lvl3 lvl4 lvl5 price
8968653 ABC Milk Mother Toddler Porridge 69
8968653 ABC AB Baby Bayi 95
代码和产品名称是公共(public)字段。 所有其他列应根据以下条件分组:
两个单元格都是空的:显示 NaN
一个单元格为空:显示其他值
两个单元格都是非空的:通过管道合并单元格
价格列应显示平均值
预期输出:
code product brand lvl1 lvl2 lvl3 lvl4 lvl5 price
8968653 ABC AB Milk Mother|Baby Toddler NaN Porridge|Bayi 82
请您参考如下方法:
我们可以分几步完成:
- 首先我们得到一个列的列表,这些列是
string类型和numeric - 其次我们使用
groupby.agg或groupby.mean取决于我们是否有string列或numeric列: - 我们清理我们的数据框,其中有不必要的
|。
# 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
