Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

python - Find different rows between 2 dataframes of different size with Pandas

I have 2 dataframes df1 and df2 of different size.

df1 = pd.DataFrame({'A':[np.nan, np.nan, np.nan, 'AAA','SSS','DDD'], 'B':[np.nan,np.nan,'ciao',np.nan,np.nan,np.nan]})
df2 = pd.DataFrame({'C':[np.nan, np.nan, np.nan, 'SSS','FFF','KKK','AAA'], 'D':[np.nan,np.nan,np.nan,1,np.nan,np.nan,np.nan]})

My goal is to identify the elements of df1 which do not appear in df2.

I was able to achieve my goal using the following lines of code.

df = pd.DataFrame({})
for i, row1 in df1.iterrows():

    found = False
    for j, row2, in df2.iterrows():

        if row1['A']==row2['C']:

            found = True
            print(row1.to_frame().T)

    if found==False and pd.isnull(row1['A'])==False:
        df = pd.concat([df, row1.to_frame().T], axis=0)

df.reset_index(drop=True)

Is there a more elegant and efficient way to achieve my goal?

Note: the solution is

    A   B
0   DDD NaN
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe need isin withboolean indexing :

Also omit NaNs rows by default chain new condition:

#changed df2 with no NaN in C column
df2 = pd.DataFrame({'C':[4, 5, 5, 'SSS','FFF','KKK','AAA'], 
                    'D':[np.nan,np.nan,np.nan,1,np.nan,np.nan,np.nan]})
print (df2)
     C    D
0    4  NaN
1    5  NaN
2    5  NaN
3  SSS  1.0
4  FFF  NaN
5  KKK  NaN
6  AAA  NaN

df = df1[~(df1['A'].isin(df2['C']) | (df1['A'].isnull()))]
print (df)
     A    B
5  DDD  NaN

If not necessary omit NaNs if not exist in C column:

df = df1[~df1['A'].isin(df2['C'])]
print (df)
     A     B
0  NaN   NaN
1  NaN   NaN
2  NaN  ciao
5  DDD   NaN

If exist NaNs in both columns use second solution:

(input DataFrames are from question)

df = df1[~df1['A'].isin(df2['C'])]
print (df)
     A    B
5  DDD  NaN

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...