根据自定义规则将数据帧与

2024-09-28 17:05:43 发布

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

这是我想做的简化示例:

data1 = {'one':['A', 'E', 'G'], 'two':['B', 'D', 'H'], 'three':['C', 'F', 'J']}
df1 = pd.DataFrame(data1) 
df1

   one  two three
0   A   B   C
1   E   D   F
2   G   H   J

data2 = {'one':['C', 'F', 'P'], 'two':['B', 'D', 'R'], 'three':['A', 'E', 'C']}
df2 = pd.DataFrame(data2) 
df2

    one two three
0   C   B   A
1   F   D   E
2   P   R   C

我想要一个函数,它将显示如下内容:

diff(df1, df2) # this syntaks can be different

    one two three  from
0   G   H   J      df1
1   P   R   C      df2

基本上在两个dataFrames中都为第二列找到文本,如果一列和三列是相反的,那么就可以了,不要将它添加到新的框架中。你知道吗

我知道如何做一个循环,但想知道什么是熊猫这样做的方式。你知道吗


Tags: 函数示例内容dataframediffthisonepd
2条回答

简单地说,只需比较您希望相同的列并对其进行筛选。在您的示例中:

pd.concat([df.loc[df1["two"] != df2["two"]] for df in (df1, df2)], axis=0)

编辑:如果您还需要“发件人”列,请将上面的行更改为:

pd.concat([df.loc[df1["two"] != df2["two"]].assign(from_df=df_name) for df, df_name in zip((df1, df2), ("df1", df2)], axis=0)

使用^{}

df1.set_index(df1.apply(frozenset, 1), inplace=True)
df2.set_index(df2.apply(frozenset, 1), inplace=True)

df1['from'] = 'df1'
df2['from'] = 'df2'

new_df = pd.concat([df1, df2]).loc[df1.index ^ df2.index].reset_index(drop=True)

print(new_df)

输出:

  one three two from
0   G     J   H  df1
1   P     C   R  df2

相关问题 更多 >