A
A
Asya2020-09-18 16:06:03
Python
Asya, 2020-09-18 16:06:03

How to do left join on pandas?

5f64afe514e29124687592.png

I have df1 and df2 dataframes,
how can I merge them to get a df that has only those values ​​that are in df1, but not in df2?

how to do this in python?
5f64b0a043514078551084.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
ScriptKiddo, 2020-09-18
@asyaevloeva

Smoking docs
https://pandas.pydata.org/docs/user_guide/merging.html

LEFT JOIN

In [42]: left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
   ....:                      'key2': ['K0', 'K1', 'K0', 'K1'],
   ....:                      'A': ['A0', 'A1', 'A2', 'A3'],
   ....:                      'B': ['B0', 'B1', 'B2', 'B3']})
   ....: 

In [43]: right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
   ....:                       'key2': ['K0', 'K0', 'K0', 'K0'],
   ....:                       'C': ['C0', 'C1', 'C2', 'C3'],
   ....:                       'D': ['D0', 'D1', 'D2', 'D3']})
   ....: 

In [44]: result = pd.merge(left, right, how='left', on=['key1', 'key2'])

5f64b1d682a67686573021.png

"LEFT ONLY JOIN"
import pandas as pd
key = 'key'

left = pd.DataFrame({key: ['1', '2', '3', '4']})

right = pd.DataFrame({key: ['5', '4', '3', '2']})

df = pd.merge(left, right, on=key, how="outer", indicator=True)
print('Merged')
print(df)
df = df[df['_merge'] == 'left_only']
print('Result')
print(df)

Merged
  key      _merge
0   1   left_only
1   2        both
2   3        both
3   4        both
4   5  right_only
Result
  key     _merge
0   1  left_only

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question