python - 删除 groupby 中的第 n 行

标签 python pandas dataframe group-by

我想删除 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/

相关文章:

python - Pandas 与另一列的最大值聚合分组?

python - 取出 CSV 的一些内容

python - 将 pandas 列从对象转换为字符串或 int/float 类型是否有必要或有益?

python - 如何使用 psycopg2 更新 postgresql 中多行的多列

python - 从 0 到 n 的数字中数字出现的次数

python - 修剪数据集词汇

python - 将重复项替换为数据框中的第一个值

python - 计算列表中每个项目在 pandas 数据框列中出现的次数,用逗号分隔值以及其他列的附加聚合

python-2.7 - Pandas DataFrame 中两个日期之间的差异

python - 在 vscode 中尽可能使用 pipenv