删除groupby中的第n行

时间:2016-07-14 04:13:50

标签: python pandas dataframe group-by

我想删除groupby对象的第n行,比如说最后一行。我可以使用# Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false

提取此行

是否有类似的方法来删除第n行,或等效地获取除第n行以外的所有行?

2 个答案:

答案 0 :(得分:3)

您可以找到所有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

答案 1 :(得分:0)

假设df是您的数据框。

df.groupby(something_to_group_by).apply(lambda x: x.iloc[:-1, :]).reset_index(0, drop=True).sort_index()