我想删除 groupby 对象的第 n 行,比如最后一行。我可以使用 groupby.nth
有没有类似的方法去掉第n行,或者等价的得到除第n行以外的所有行?
最佳答案
您可以找到所有 nth
的索引行,然后选择 Index.difference
通过 ix
:
import pandas as pd
df = pd.DataFrame({'A':[1,1,1,2,2,2],
'B':[4,5,6,7,8,9]})
print (df)
A B
0 1 4
1 1 5
2 1 6
3 2 7
4 2 8
5 2 9
print (df.ix[df.index.difference(df.groupby('A', as_index=False)['B'].nth(1).index)])
A B
0 1 4
2 1 6
3 2 7
5 2 9
idx = df.groupby('A', as_index=False)['B'].nth(1).index
print (idx)
Int64Index([1, 4], dtype='int64')
print (df.index.difference(idx))
Int64Index([0, 2, 3, 5], dtype='int64')
print (df.ix[df.index.difference(idx)])
A B
0 1 4
2 1 6
3 2 7
5 2 9
如果需要没有最后一行的所有行,使用GroupBy.tail
:
print (df.ix[df.index.difference(df.groupby('A')['B'].tail(1).index)])
A B
0 1 4
1 1 5
3 2 7
4 2 8
时间:
In [27]: %timeit (df.groupby('A').apply(lambda x: x.iloc[:-1, :]).reset_index(0, drop=True).sort_index())
100 loops, best of 3: 2.48 ms per loop
In [28]: %timeit (df.ix[df.index.difference(df.groupby('A')['B'].tail(1).index)])
1000 loops, best of 3: 1.29 ms per loop
In [29]: %timeit (df.ix[df.index.difference(df.groupby('A', as_index=False)['B'].nth(1).index)])
The slowest run took 4.42 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.48 ms per loop
关于python - 删除 groupby 中的第 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38365363/