如何组合 pandas 中的重复行? [英] How to combine duplicate rows in pandas?
本文介绍了如何组合 pandas 中的重复行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何合并pandas中的重复行,填补缺失值?
How to combine duplicate rows in pandas, filling in missing values?
在下面的示例中,某些行在 c1
列中有缺失值,但 c2
列有重复项,可以用作索引来查找和填充在那些缺失值中.
In the example below, some rows have missing values in the c1
column, but the c2
column has duplicates that can be used as an index to look up and fill in those missing values.
输入数据如下所示:
c1 c2
id
0 10.0 a
1 NaN b
2 30.0 c
3 10.0 a
4 20.0 b
5 NaN c
所需的输出:
c1 c2
0 10 a
1 20 b
2 30 c
但是如何做到这一点?
这是生成示例数据的代码:
Here is the code to generate the example data:
import pandas as pd
df = pd.DataFrame({
'c1': [10, float('nan'), 30, 10, 20, float('nan')]
'c2': [100, 200, 300, 100, 200, 300],
})
推荐答案
我认为需要 sort_values
和 drop_duplicates
:
I think need sort_values
with drop_duplicates
:
df = df.sort_values(['c1','c2']).drop_duplicates(['c2'])
print (df)
c1 c2
0 10.0 100
4 20.0 200
2 30.0 300
或者首先通过 NaN 的行="nofollow noreferrer">dropna
:
Or first remove rows with NaN
s by dropna
:
df = df.dropna(subset=['c1']).drop_duplicates(['c2'])
print (df)
c1 c2
0 10.0 100
2 30.0 300
4 20.0 200
<小时>
df = df.dropna(subset=['c1']).drop_duplicates(['c1','c2'])
print (df)
c1 c2
0 10.0 100
2 30.0 300
4 20.0 200
这篇关于如何组合 pandas 中的重复行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文