Мы можем сделать это в несколько шагов:
- Сначала мы получаем список столбцов типа
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