【问题标题】:How to remove rows in a Pandas dataframe if there exits matches across a set of columns in another dataframe?如果在另一个数据框中的一组列中存在匹配项,如何删除 Pandas 数据框中的行?
【发布时间】:2021-08-11 19:31:10
【问题描述】:

我在数据框中有一组人,我需要主数据集中没有出现的人员列表。目前我正在检查名字和姓氏。

data_to_check_dataset是需要检查的输入数据,它包含很多列,但目前我只需要检查first_namelast_name

first_name last_name ...
0 James Apple ...
1 Alice test ...
... ... ... ...
10000 Paul test ...

有时数据字段可能完全为空白,并被读取为 nan 值。

first_name last_name ...
0 James comp nan ...
1 Paul ltd nan ...
... ... ... ...
10000 Paul other nan ...

我正在检查 current_people_dataset 的数据框:它包含许多列,我已将名称列重命名为 first_namelast_name。由于某种原因,它的空值是空白的,我认为是因为

first_name last_name ...
0 f_A l_A ...
1 B ...
... ... ... ...
900000 paul smith ...

data_to_check_dataset 总是小于current_people_dataset。 列顺序不是固定的,可以根据从此处加载数据的位置而改变。

目前我一直在尝试改编here的代码。

new_people_names = (pd.merge(data_to_check_dataset,current_people_dataset, indicator=True, how='outer')
         .query('_merge=="left_only"')
         .drop('_merge', axis=1))

这会在比较列时引发ValueError: You are trying to merge on float64 and object columns. If you wish to proceed you should use pd.concat 错误。

【问题讨论】:

  • 对不起,我不知道为什么它会删除答案,我没有删除它。

标签: python pandas


【解决方案1】:

这就是错误的意思,因此一种方法是使用astype() 将两个df 的first_name 和last_name 类型化为字符串:

data_to_check_dataset[['first_name','last_name']]=data_to_check_dataset[['first_name','last_name']].astype(str)
current_people_dataset[['first_name','last_name']]=current_people_dataset[['first_name','last_name']].astype(str)

最后将replace() 链接到您当前将字符串 nan 转换回真实 NaN 的方法:

new_people_names = (pd.merge(data_to_check_dataset,current_people_dataset, indicator=True, how='outer',on=['first_name','last_name'])
         .query('_merge=="left_only"')
         .drop('_merge', axis=1)
         .replace('nan',float('NaN'),regex=True))

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 2021-11-13
    • 2020-10-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多