在 pandas 数据框中为每个组插入缺少的类别 [英] insert missing category for each group in pandas dataframe

查看:46
本文介绍了在 pandas 数据框中为每个组插入缺少的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为每个组插入缺失的类别,例如:

I need to insert missing category for each group, here is an example:

import pandas as pd
import numpy as np

df = pd.DataFrame({ "group":[1,1,1 ,2,2],
                   "cat": ['a', 'b', 'c', 'a', 'c'] ,
                   "value": range(5),
                   "value2": np.array(range(5))* 2})

df

# test dataframe

cat group   value value2
a   1         0   0
b   1         1    2
c   1         2    4
a   2         3    6
c   2         4    8

说我有一些类别= ['a','b','c','d'] 。如果 cat
不包含列表中的类别,我想为每个值a行> 0 。
如何在类别中每组插入一行,以便获取每个组的所有类别

say I have some categories = ['a', 'b', 'c', 'd']. if cat column does not contain a category from the list, I would like to insert a row, for each group with value 0. how to insert a row per group if category, so as to get all the categories for each group

cat group   value  value2
a   1         0    0
b   1         1    2
c   1         2    4
d   1         0    0
a   2         3    6
c   2         4    8
b   2         0    0
d   2         0    0


推荐答案

有点复杂,但您可以使用 groupby + reindex

A bit complicated, but you can use groupby + reindex:

categories = ['a', 'b', 'c', 'd']

def f(x):
    return x.reindex(categories, fill_value=0)\
                   .assign(group=x['group'][0].item())

df.set_index('cat').groupby('group', group_keys=False).apply(f).reset_index()


  cat  group  value  value2
0   a      1      0       0
1   b      1      1       2
2   c      1      2       4
3   d      1      0       0
4   a      2      3       6
5   b      2      0       0
6   c      2      4       8
7   d      2      0       0

这篇关于在 pandas 数据框中为每个组插入缺少的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆