给定两个具有分组项的数据帧和另一个具有等效组的数据帧,我可以使用匹配组中的所有单元对创建一个数据帧吗?

2024-10-02 10:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个数据帧df1

   df1_unit   base_unit
0     x         x
1     y         x
2     z         z
3     t         z
4     u         z

还有一个叫做df2

   df2_unit   base_unit
0     a         b
1     b         b
2     c         c
3     d         e
4     e         e

还有另一个数据帧df_eq,它给出了组之间的等价性:

   df1_unit   df2_unit
0     x         b
1     z         e

df1的情况下,base_unit基本上是充当组中所有单元的父单元的df1_unit。i、 e.x是将xyz单元标识为组的基本单元。类似地df2

我试图生成一个数据帧,其中包含来自等价组的所有可能的项对,但不包含df_eq数据帧中的项对(这是我们施加的限制)。在这种情况下,无限制输出为:

   df1_unit   df2_unit
0     x         a
1     x         b       (shouldn't be included)
2     y         a
3     y         b
4     z         d
5     z         e       (shouldn't be included)
6     t         d
7     t         e
8     u         d
9     u         e

所需的受限输出将是

   df1_unit   df2_unit
0     x         a
1     y         a
2     y         b
3     z         d
4     t         d
5     t         e
6     u         d
7     u         e

我很难在不使用荒谬的暴力方法的情况下生成无限制的输出。是否有一种有效的方法来实现期望的输出

编辑:我使用以下代码取得了一些进展:

temp = dfeq.rename(columns={'df2u':'base_unit'}).merge(df2, on='base_unit', how='left')
temp = temp[['df1u', 'df2u']]
out = temp.rename(columns={'df1u':'base_unit'}).merge(df1, on='base_unit', how='left')
out = out[['df1u', 'df2u']]

这似乎正确吗?另外,我不确定如何删除out中也存在于dfeq中的行


Tags: 数据dfbase情况unitouttemp单元
1条回答
网友
1楼 · 发布于 2024-10-02 10:33:36

您可以使用以下方法:

  1. 考虑到df_eq中的数据,我们将在df1中映射base_unit列,因为我们将使用^{}构建一个字典,该字典将由^{}方法使用

    map_base_unit_df2 = dict(df_eq.to_dict(orient='split')['data']) 
    df1['base_unit'] = df1['base_unit'].map(map_base_unit_df2)
    
  2. 我们将使用^{}构建df_unrestricted,只选择对我们来说重要的列

    df_unrestricted = pd.merge(df1, df2, on='base_unit')[['df1_unit', 'df2_unit']]
    
  3. 最后,添加最后一个限制,我的意思是,我们将使用^{}+^{}+^{}删除df_eq中存在的记录

    df_output = pd.concat([df_unrestricted, df_eq]).drop_duplicates(keep=False).reset_index(drop=True)
    

完整代码:

map_base_unit_df2 = dict(df_eq.to_dict(orient='split')['data']) 
df1['base_unit'] = df1['base_unit'].map(map_base_unit_df2)
df_unrestricted = pd.merge(df1, df2, on='base_unit')[['df1_unit', 'df2_unit']]
df_output = pd.concat([df_unrestricted, df_eq]).drop_duplicates(keep=False).reset_index(drop=True)
print(df_output)

输出:

   df1_unit df2_unit
0      x       a
1      y       a
2      y       b
3      z       d
4      t       d
5      t       e
6      u       d
7      u       e

相关问题 更多 >

    热门问题