gpt4 book ai didi

python - 当列中有多个具有重复值的行时选择第一行

转载 作者:行者123 更新时间:2023-12-03 23:27:40 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Get Rows based on distinct values from Column 2

(1 个回答)


去年关闭。




当一列中有多个具有重复值的行时,我想选择第一行。

例如:

import pandas as pd
df = pd.DataFrame({'col1':['one', 'one', 'one', 'one', 'one', 'one', 'one', 'one'],
'col2':['ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD1234', 'ID=ABCD5678',
'ID=ABCD5678', 'ID=ABCD5678', 'ID=ABCD9102', 'ID=ABCD9102']})

Pandas 数据框如下所示:
print(df)
col1 col2
0 one ID=ABCD1234
1 one ID=ABCD1234
2 one ID=ABCD1234
3 one ID=ABCD5678
4 one ID=ABCD5678
5 one ID=ABCD5678
6 one ID=ABCD9102
7 one ID=ABCD9102

我希望第 0 行、第 3 行和第 6 行被选中并作为新数据帧输出。

预期输出:
      col1         col2
0 one ID=ABCD1234
3 one ID=ABCD5678
6 one ID=ABCD9102

最佳答案

您可以使用:

df.drop_duplicates(subset = ['col2'], keep = 'first', inplace = True) 

关于python - 当列中有多个具有重复值的行时选择第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60294634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com