在 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 包含 AB20、AB10 和 AB17,与 dataframe_1 相同,顺序随机。
如何检查 dataframe_2 中的哪些元素是新元素,哪些元素与 dataframe_1 相同???
最佳答案
我认为需要isin
对于 bool 掩码和过滤器 loc
与 boolean 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/