Python Pandas-如果在列中重复某个特定值,则删除该行,并保留第一个值
假设我们有一个数据帧:Python Pandas-如果在列中重复某个特定值,则删除该行,并保留第一个值,python,pandas,Python,Pandas,假设我们有一个数据帧: num line 0 1 56 1 1 90 2 2 66 3 3 4 4 3 55 5 3 104 6 1 23 7 5 22 8 3 144 # True where num is 3 c1 = df['num'].eq(3) # True where num is repeated c2 = df['num'].eq(df['num'
num line
0 1 56
1 1 90
2 2 66
3 3 4
4 3 55
5 3 104
6 1 23
7 5 22
8 3 144
# True where num is 3
c1 = df['num'].eq(3)
# True where num is repeated
c2 = df['num'].eq(df['num'].shift(1))
# boolean indexation on df
df[(c1 & ~c2) | ~(c1)]
num line
0 1 56
1 1 90
2 2 66
3 3 4
6 1 23
7 5 22
8 3 144
我想删除num列中重复3的行,并保留第一行。因此,num列中重复1的两行应该仍然与所有其他列一起位于结果数据帧中
到目前为止,我所拥有的,消除了每一个双精度值,而不仅仅是3:
data.groupby((data['num'] != data['num'].shift()).cumsum().values).first()
预期结果或正确代码:
num line
0 1 56
1 1 90
2 2 66
3 3 4
4 1 23
5 5 22
6 3 144
您可以使用以下条件在数据帧中执行布尔索引:
num line
0 1 56
1 1 90
2 2 66
3 3 4
4 3 55
5 3 104
6 1 23
7 5 22
8 3 144
# True where num is 3
c1 = df['num'].eq(3)
# True where num is repeated
c2 = df['num'].eq(df['num'].shift(1))
# boolean indexation on df
df[(c1 & ~c2) | ~(c1)]
num line
0 1 56
1 1 90
2 2 66
3 3 4
6 1 23
7 5 22
8 3 144
细节
您可以使用以下条件在数据帧中执行布尔索引:
num line
0 1 56
1 1 90
2 2 66
3 3 4
4 3 55
5 3 104
6 1 23
7 5 22
8 3 144
# True where num is 3
c1 = df['num'].eq(3)
# True where num is repeated
c2 = df['num'].eq(df['num'].shift(1))
# boolean indexation on df
df[(c1 & ~c2) | ~(c1)]
num line
0 1 56
1 1 90
2 2 66
3 3 4
6 1 23
7 5 22
8 3 144
细节
使用:
详细信息:
比较是否不相等:
print (data['num'].ne(3))
0 True
1 True
2 True
3 False
4 False
5 False
6 True
7 True
8 False
Name: num, dtype: bool
按移位值比较第一个连续的:
print (data['num'].ne(data['num'].shift()))
0 True
1 False
2 True
3 True
4 False
5 False
6 True
7 True
8 True
Name: num, dtype: bool
按位或的链接:
print (data['num'].ne(3) | data['num'].ne(data['num'].shift()))
0 True
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
Name: num, dtype: bool
使用:
详细信息:
比较是否不相等:
print (data['num'].ne(3))
0 True
1 True
2 True
3 False
4 False
5 False
6 True
7 True
8 False
Name: num, dtype: bool
按移位值比较第一个连续的:
print (data['num'].ne(data['num'].shift()))
0 True
1 False
2 True
3 True
4 False
5 False
6 True
7 True
8 True
Name: num, dtype: bool
按位或的链接:
print (data['num'].ne(3) | data['num'].ne(data['num'].shift()))
0 True
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
Name: num, dtype: bool
好吧,我可以使用几个只执行解决方案一部分的子数据帧,然后将它们组合起来。我从来没有这样想过!谢谢好吧,我可以使用几个只执行解决方案一部分的子数据帧,然后将它们组合起来。我从来没有这样想过!谢谢感谢您了解我,我可以组合几个提供解决方案一部分的子数据帧,然后组合它们!!很好!感谢您了解我,我可以组合几个提供解决方案一部分的子数据帧,然后组合它们!!很好!