简体   繁体   English

根据对另一个 dataframe 的条件检查,过滤来自一个 dataframe 的值

[英]Filter values from one dataframe based on conditional checks on another dataframe

Consider these two dataframes (simplified example):考虑这两个数据框(简化示例):

DF1
     Name  Age
0    Tom   20
1   nick   21
2  krish   19
3   jack   18


DF2
     Name  Age
0    krish 40
1    jack  18
2    Tom   50
3    Jim   21

Note that the indices for a Name appearing in both doesn't match (this is the case for my dataset).请注意,出现在两者中的名称索引不匹配(我的数据集就是这种情况)。

I would like to select those rows from DF1 where the Name is in DF2 and Age for that person doesn't match the corresponding value in DF2.我想 select 来自 DF1 的那些行,其中名称在 DF2 中,并且该人的年龄与 DF2 中的相应值不匹配。 So the expected output is:所以预期的 output 是:

     Name  Age
0    Tom   20
2  krish   40

I can filter rows that match one condition (eg Name is in DF2), but I've not been able to figure out how to check both conditions together.我可以过滤与一个条件匹配的行(例如,名称在 DF2 中),但我无法弄清楚如何同时检查这两个条件。 Any ideas?有任何想法吗?

In: df1[df1['Name'].isin(df2['Name'].tolist())]
Out: 
        Name    Age
    0   Tom 20
    2   krish   19
    3   jack    18

You can use merge before filter out your dataframe:您可以在过滤掉 dataframe 之前使用merge

>>> df1.merge(df2, on='Name', how='left', suffixes=('', '2')) \
       .query('Age != Age2')[df1.columns]

    Name  Age
0    Tom   20
1  krish   19

You do with update then compared the value to see whether it being updated您使用update然后比较该值以查看它是否正在更新

dfTemp = df1.copy()
dfTemp = df1.set_index('Name').copy()
dfTemp.update(df2.set_index('Name'))
df1[df1.Age!=dfTemp.Age.values]
Out[405]: 
    Name  Age
0    Tom   20
2  krish   19

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据特定月份的值过滤熊猫数据框,并以另一列为条件 - Filter a pandas Dataframe based on specific month values and conditional on another column 根据条件从另一个数据帧的值替换一个数据帧的值 - substitue values of one dataframe from values of another dataframe based on condition 通过另一个DataFrame中的唯一值过滤一个DataFrame - Filter one DataFrame by unique values in another DataFrame 根据两者的索引将一个数据帧中的值填充到另一个数据帧中 - Fill values from one dataframe into another dataframe based on index of the two Pandas,根据一列中的唯一值和另一列中的 grouby 筛选 dataframe - Pandas, filter dataframe based on unique values in one column and grouby in another 根据另一个数据框中的值从DataFrame中选择行,并根据第二个DataFrame使用值更新其中一个列 - Select rows from a DataFrame based on a values in another dataframe and updating one of the column with values according to the second DataFrame 基于过滤器添加新列并添加来自另一个 DataFrame 的值 - Add new columns and add values from another DataFrame based on a filter 总和 dataframe 基于来自另一个 dataframe 的值 - sum dataframe based on values from another dataframe Pandas 根据另一个数据框中 2 列的值过滤行 - Pandas filter rows based on values from 2 columns in another dataframe 根据来自另一个数据帧的值更新数据帧 - Update a dataframe based on values from another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM