Pandas 仅保留重复列上的第一个值(将0设置为其他值)
假设我有以下情况: 第一列Pandas 仅保留重复列上的第一个值(将0设置为其他值),pandas,numpy,Pandas,Numpy,假设我有以下情况: 第一列['ID']最终将具有重复值的数据帧 import pandas as pd df = pd.DataFrame({"ID": [1,2,3,4,4,5,5,5,6,6], "l_1": [10,12,32,45,45,20,20,20,20,20], "l_2": [11,12,32,11,21,27,38,12,9,6],
['ID']
最终将具有重复值的数据帧
import pandas as pd
df = pd.DataFrame({"ID": [1,2,3,4,4,5,5,5,6,6],
"l_1": [10,12,32,45,45,20,20,20,20,20],
"l_2": [11,12,32,11,21,27,38,12,9,6],
"l_3": [5,9,32,12,21,21,18,12,8,1],
"l_4": [6,21,12,77,77,2,2,2,8,8]})
ID l_1 l_2 l_3 l_4
1 10 11 5 6
2 12 12 9 21
3 32 32 32 12
4 45 11 12 77
4 45 21 21 77
5 20 27 21 2
5 20 38 18 2
5 20 12 12 2
6 20 9 8 8
6 20 6 1 8
出现重复ID时:
- 我只需要保留列
和l_1
的第一个值(其他重复的行必须为零)l_4
- 列“l_2”和“l_3”必须保持不变
- 出现重复ID时,l_1和l_4列上这些行上的值也将重复
ID l_1 l_2 l_3 l_4
1 10 11 5 6
2 12 12 9 21
3 32 32 32 12
4 45 11 12 77
4 0 21 21 0
5 20 27 21 2
5 0 38 18 0
5 0 12 12 0
6 20 9 8 8
6 0 6 1 0
有没有一种简单的方法可以使用熊猫或numpy来实现这一点
我可以通过以下步骤来完成:
x1 = df[df.duplicated(subset=['ID'], keep=False)].copy()
x1.loc[x1.groupby('ID')['l_1'].apply(lambda x: (x.shift(1) == x)), 'l_1'] = 0
x1.loc[x1.groupby('ID')['l_4'].apply(lambda x: (x.shift(1) == x)), 'l_4'] = 0
df = df.drop_duplicates(subset=['ID'], keep=False)
df = pd.concat([df, x1])
这不只是:
df.loc[df.duplicated('ID'), ['l_1','l_4']] = 0
输出:
ID l_1 l_2 l_3 l_4
0 1 10 11 5 6
1 2 12 12 9 21
2 3 32 32 32 12
3 4 45 11 12 77
4 4 0 21 21 0
5 5 20 27 21 2
6 5 0 38 18 0
7 5 0 12 12 0
8 6 20 9 8 8
9 6 0 6 1 0
嗨,光环,这就是我要找的。我的方法有许多不必要的步骤。非常感谢。