python - for 循环中的 pandas isin 函数

标签 python pandas dataframe for-loop isin

1.csv

     cut  price  depth  carat  table
0   Good    327   57.9   0.23   65.0
1   Good    335   63.3   0.31   58.0
2 Very Good 336   62.8   0.24   57.0
3 Very Good 336   62.3   0.24   57.0
4 Very Good 337   61.9   0.26   55.0
5 Premium   326   59.8   0.21   61.0
6  Premium  334   62.4   0.29   58.0
7   Good    400   64.0   0.30   55.0

2.csv

     cut  price  depth  carat  table
0   Good    327   57.9   0.23   65.0
1   Good    335   63.3   0.31   58.0
2 Very Good 336   62.8   0.24   57.0
3 Very Good 336   62.3   0.24   57.0
4 Very Good 337   61.9   0.26   50.0
5 Premium   326   59.8   0.21   61.0
6  Premium  334   60.4   0.29   58.0
7   Good    399   64.0   0.30   55.0

2.csv 仅更改了 4,6,7 行

我正在寻找

输出如下

     cut  price  depth  carat  table
4 Very Good 337   61.9   0.26   50.0
6  Premium  334   60.4   0.29   58.0
7   Good    399   64.0   0.30   55.0

任何人都可以分享您的经验吗?任何形式的帮助都可以

import pandas as pd
f1 = pd.read_csv('1.csv')
f2 = pd.read_csv('2.csv')
columns_list = ['cut', 'price', 'depth', 'carat', 'table']

new_df= f2[~f2.price.isin(f1.price)]
print(new_df)

这是我编写的示例代码,它工作正常,但我需要使用

f2[~f2.price.isin(f1.price)]

在循环中获取“价格”空间上的每个列名称,并且还将返回值。我尝试像这样的正常方式

for i in columns_list:
price = f2[~f2.i.isin(f1.i)]
print(price)

但是 pandas 命令不能像这样工作,它会返回类似的错误

AttributeError: 'DataFrame' object has no attribute 'i'

感谢您的阅读,希望您能理解

最佳答案

IIUC,DataFrame.merge指示器= True:

f2_filtered = (f2.merge(f1, how='outer', indicator=True)
                 .query('_merge == "left_only"')
                 .drop(columns = '_merge'))
print(f2_filtered)

输出

         cut  price  depth  carat  table
4  Very_Good    337   61.9   0.26   50.0
6    Premium    334   60.4   0.29   58.0
7       Good    399   64.0   0.30   55.0

关于python - for 循环中的 pandas isin 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60975485/

相关文章:

python - 操作后将 pandas 数据帧保存在循环中

python - 如何根据本地目录中的 requirements.txt 文件使用 pip 安装软件包?

python - 如何根据opencv python中的掩码删除图像组件?

python - TableView 中的行数意外影响交替行颜色

python - 将 pandas.Series.value_counts 返回的系列转换为字典

r - 变量前的美元符号

python - 从 python 守护进程启动线程的正确方法

python - Pandas - 数据框名称列表?

python - 从首字母为小写的数据框中删除行

python - 在 pandas 中,如何在数据框中显示最常见的诊断,但只计算每个患者出现 1 次相同的诊断