仅当列值相同时才合并数据框

时间:2020-11-05 12:04:06

标签: python pandas dataframe

我有两个数据帧dfdf_copy。我想从df_copy复制数据,但前提是数据也相同。我该怎么办?

import pandas as pd

d = {'Nameid': [100, 200, 300, 100]
     , 'Name': ['Max', 'Michael', 'Susan', 'Max']
     , 'Projectid': [100, 200, 200, 100]}

df = pd.DataFrame(data=d)
display(df.head(5))

df['nameid_index'] = df['Nameid'].astype('category').cat.codes
df['projectid_index'] = df['Projectid'].astype('category').cat.codes
display(df.head(5))

df_copy = df.copy()

df.drop(['Nameid', 'Name', 'Projectid'], axis=1, inplace=True)
df = df.drop([1, 3])
display(df.head(5))

df

enter image description here

df_copy

enter image description here

我想要的

enter image description here


我看着Pandas Merging 101

df.merge(df_copy, on=['nameid_index', 'projectid_index'])

但是我得到了这个结果

enter image description here

同一行是两次,我只想要一次。

1 个答案:

答案 0 :(得分:2)

首先使用DataFrame.drop_duplicates

with

如果需要通过两个df1 = (df.drop_duplicates(['nameid_index', 'projectid_index']) .merge(df_copy, on=['nameid_index', 'projectid_index'])) 中的列名交叉来合并,则应删除DataFrame参数:

on