Pandas/Python: How to concatenate two dataframes without duplicates?(Pandas/Python:如何连接两个没有重复的数据帧?)
问题描述
我想将两个数据帧 A、B 连接到一个没有重复行的新数据帧(如果 B 中的行已经存在于 A 中,则不要添加):
I'd like to concatenate two dataframes A, B to a new one without duplicate rows (if rows in B already exist in A, don't add):
数据框 A:数据框 B:
Dataframe A: Dataframe B:
I II I II
0 1 2 5 6
1 3 1 3 1
新数据框:
I II
0 1 2
1 3 1
2 5 6
我该怎么做?
推荐答案
最简单的方法是只进行连接,然后删除重复项.
The simplest way is to just do the concatenation, and then drop duplicates.
>>> df1
A B
0 1 2
1 3 1
>>> df2
A B
0 5 6
1 3 1
>>> pandas.concat([df1,df2]).drop_duplicates().reset_index(drop=True)
A B
0 1 2
1 3 1
2 5 6
reset_index(drop=True)
是修复concat()
和drop_duplicates()
之后的索引.没有它,您将拥有 [0,1,0]
的索引,而不是 [0,1,2]
.如果不立即重置,这可能会导致对该 dataframe
的进一步操作出现问题.
The reset_index(drop=True)
is to fix up the index after the concat()
and drop_duplicates()
. Without it you will have an index of [0,1,0]
instead of [0,1,2]
. This could cause problems for further operations on this dataframe
down the road if it isn't reset right away.
这篇关于Pandas/Python:如何连接两个没有重复的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Pandas/Python:如何连接两个没有重复的数据帧?


基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01