首页 > 解决方案 > 根据条件将缺失的行从一个数据帧添加到另一个数据帧

问题描述

我的示例数据如下:

data1 = {'index':  ['001', '001', '001', '002', '002', '003', '004','004'],
        'type' : ['red', 'red', 'red', 'yellow', 'red', 'green', 'blue', 'blue'],
        'class' : ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']}
df1 = pd.DataFrame (data1, columns = ['index', 'type', 'class']) 
df1
    index   type    class
0   001     red     A
1   001     red     A
2   001     red     A
3   002     yellow  A
4   002     red     A
5   003     green   A
6   004     blue    A
7   004     blue    A

data2 = {'index':  ['001', '001', '002', '003', '004'],
        'type' : ['red', 'red', 'yellow', 'green', 'blue'],
        'class' : ['A', 'A', 'A', 'B', 'A'],
        'outcome': ['in', 'in', 'out', 'in', 'out']}
df2 = pd.DataFrame (data2, columns = ['index', 'type', 'class', 'outcome']) 
df2
    index   type    class   outcome
0   001     red     A       in
1   001     red     A       in
2   002     yellow  A       out
3   003     green   B       in
4   004     blue    A       out

df1, 在class = A, 在df2它可以是A,BC. 我想在df2from中添加缺少的行df1df1具有每个索引的类型计数。例如,如果 in df1index001出现 3 次,则意味着我也应该在df2. 对于df1不在 中的行df2,列outcome应等于 NaN。输出应该是:

    index   type    class   outcome
0   001     red     A       in
1   001     red     A       in
2   001     red     A       NaN
3   002     yellow  A       out
4   002     red     A       NaN
5   003     green   A       NaN
6   003     green   B       in
7   004     blue    A       out
8   004     blue    A       NaN

我尝试使用 pd.concat 和 pd.merge 但我不断收到重复或添加错误的行。有人知道如何做到这一点吗?

标签: pythonpandasdataframe

解决方案


用于唯一性的计数器值,因此可能在下一步中GroupBy.cumcount使用外连接:DataFrame.merge

df1['group'] = df1.groupby(['index','type','class']).cumcount()
df2['group'] = df2.groupby(['index','type','class']).cumcount()

df = (df1.merge(df2, on=['index','type','class','group'], how='outer')
         .sort_values(by=['index', 'class'])
         .drop(columns='group'))
print (df)
  index    type class outcome
0   001     red     A      in
1   001     red     A      in
2   001     red     A     NaN
3   002  yellow     A     out
4   002     red     A     NaN
5   003   green     A     NaN
8   003   green     B      in
6   004    blue     A     out
7   004    blue     A     NaN

推荐阅读