假设我有一个数据帧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
是将x
、y
、z
单元标识为组的基本单元。类似地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
中的行
您可以使用以下方法:
考虑到} 构建一个字典,该字典将由^{} 方法使用
df_eq
中的数据,我们将在df1
中映射base_unit
列,因为我们将使用^{我们将使用^{} 构建
df_unrestricted
,只选择对我们来说重要的列最后,添加最后一个限制,我的意思是,我们将使用^{} +^{} +^{} 删除
df_eq
中存在的记录完整代码:
输出:
相关问题 更多 >
编程相关推荐