Home » Python » python – is there a function to delete (in df1) the different rows in two df?-Exceptionshub

python – is there a function to delete (in df1) the different rows in two df?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have two DataFrame with different length. In df1 i need to keep just the rows of df1 that are in df2 too and delete all the rows that are not in df1.
I used the function below that finds the difference between 2 df, but i won’t be able to delete all the lines in df1.

df1[~(df1['F_Code'].isin(df2['Codice']))]
How to&Answers:

I think you are looking for this command :

pandas.merge(df,df2,how='inner')

you can know more about pandas.merge here https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html.

This is quite like the SQL JOIN keyword.

representation of sql join keyword

Answer:

Looks like you want to merge two data frames on columns with a different column name. In that case this is what you need:

import pandas as pd

# Create Example data
df1 = pd.DataFrame({'F_Code': [1,2, 8], 'a': [3,4,5]})
df2 = pd.DataFrame({'Codice': [1,2,3], 'b': [1,2,5]})

df = pd.merge(df1, df2, how='inner', left_on='F_Code', 
              right_on='Codice').drop(columns=df2.columns)

result:


    F_Code  a
0   1       3
1   2       4