find records in first dataframe which is not present in second data frame
- User
find records in first dataframe which is not present in second data frame
- Assistant
Assuming the two dataframes have the same columns and same number of columns, you can use the
mergefunction with theindicatorparameter set toTrueto create a column indicating the source of each row. Then, filter the rows where the source column is equal to'left_only'.Here's an example:
codeimport pandas as pd df1 = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c']}) df2 = pd.DataFrame({'A': [1, 2], 'B': ['a', 'b']}) merged = pd.merge(df1, df2, on=['A', 'B'], how='left', indicator=True) only_in_df1 = merged[merged['_merge'] == 'left_only']In this example,
df1has one extra row compared todf2. Themergeddataframe would look like:codeA B _merge 0 1 a both 1 2 b both 2 3 c left_onlyThe
_mergecolumn indicates that the first two rows are present in both dataframes, while the last row is only in . We then filter for those rows where is to get the rows that are only in . - User
pass a list of data to filter records in dataframe'
- Assistant
You can use the
isin()method to filter a dataframe based on a list of values. Here's an example:Suppose you have a dataframe
dflike this:codeName Age 0 John 25 1 Jane 30 2 Alice 27 3 Bob 22 4 Tom 33And you want to filter it based on a list of ages
[22, 27, 33], you can do:codeages = [22, 27, 33] filtered_df = df[df['Age'].isin(ages)]This will give you a new dataframe
filtered_df:codeName Age 2 Alice 27 3 Bob 22 4 Tom 33The resulting dataframe only includes the rows where the age column contains one of the values in the
ageslist.