gpt4 book ai didi

python - Pandas 根据几列减去数据框中的行

转载 作者:行者123 更新时间:2023-12-05 01:56:22 26 4
gpt4 key购买 nike

我有以下数据框

data = [
{'col1': 11, 'col2': 111, 'col3': 1111},
{'col1': 22, 'col2': 222, 'col3': 2222},
{'col1': 33, 'col2': 333, 'col3': 3333},
{'col1': 44, 'col2': 444, 'col3': 4444}
]

和以下列表:

lst = [(11, 111), (22, 222), (99, 999)]

我只想从我的数据中取出 col1 和 col2 在 lst 中不存在的行

上面例子的结果是:

[
{'col1': 33, 'col2': 333, 'col3': 3333},
{'col1': 44, 'col2': 444, 'col3': 4444}
]

我怎样才能做到这一点?

import pandas as pd

df = pd.DataFrame(data)

list_df = pd.DataFrame(lst)

# command like ??
# df.subtract(list_df)

最佳答案

如果需要成对测试是可能的,请比较由 Index.isin 中的两列创建的 MultiIndex通过 ~boolean indexing 中使用反转掩码:

df = df[~df.set_index(['col1','col2']).index.isin(lst)]
print (df)
col1 col2 col3
2 33 333 3333
3 44 444 4444

或左连接 merge带有指标参数:

m = df.merge(list_df, 
left_on=['col1','col2'],
right_on=[0,1],
indicator=True,
how='left')['_merge'].eq('left_only')
df = df[mask]
print (df)
col1 col2 col3
2 33 333 3333
3 44 444 4444

关于python - Pandas 根据几列减去数据框中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69881567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com