python - Pandas Dataframe 数据是相同的还是新的?

标签 python pandas dataframe

在 Python 中,使用 Pandas 数据帧:

数据框_1:

     id
0  AB17
1  AB18
2  AB19
3  AB20
4  AB10

数据框_2:

     id
0  AB20
1  AB10
2  AB17
3  AB21
4  AB09

这里,dataframe_2 包含 AB20AB10AB17,与 dataframe_1 相同,顺序随机。

如何检查 dataframe_2 中的哪些元素是新元素,哪些元素与 dataframe_1 相同???

最佳答案

我认为需要isin对于 bool 掩码和过滤器 locboolean indexing ,如有必要,将输出 Series 转换为 list:

mask = dataframe_2['id'].isin(dataframe_1['id'])
print (mask)
0     True
1     True
2     True
3    False
4    False
Name: id, dtype: bool

same = dataframe_2.loc[mask, 'id'].tolist()
diff = dataframe_2.loc[~mask, 'id'].tolist()

#if want unique values
#same = dataframe_2.loc[mask, 'id'].unique().tolist()
#diff = dataframe_2.loc[~mask, 'id'].unique().tolist()

print (same)
['AB20', 'AB10', 'AB17']

print (diff)
['AB21', 'AB09']

关于python - Pandas Dataframe 数据是相同的还是新的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52491327/

相关文章:

mysql - 比较两个 csv 文件的内容,其中两个文件之间的关系在第三个文件中指定?

python - Pandas 聚合: How to generate multiple new columns from one column and vise versa

python - Pandas 数据帧 : Assigning integer values based on the column value

python - 使用 Chaquopy 安装 TensorFlow 时出现 "Read timed out"

python - 使用 Python/Pandas 索引日期作为假期列表中的条件

python - 创建 for 循环以使用 Seaborn 为 DataFrame 的各个列绘制直方图

python - pandas 如何在所有浮点列均为 NaN 时删除行

python - 在 python list(map(...)) 中跟踪进度

python - 如何在 Django 中获取登录用户 ID

python - 如何导入Excel选项卡并在Python中相应地在新列中给出选项卡的名称?