跳过熊猫中的每第n行

时间:2018-03-21 10:29:29

标签: python-3.x pandas slice

我试图通过跳过每第4行来切片我的数据帧。我完成它的最好方法是获取每第4行的索引,然后选择所有其他行。如下所示: -

df[~df.index.isin(df[::4].index)]

我想知道是否有更简单和/或更多的pythonic方式来完成这项工作。

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是按模数创建掩码并按boolean indexing过滤:

df = pd.DataFrame({'a':range(10, 30)}, index=range(20))
#print (df)


b = df[np.mod(np.arange(df.index.size),4)!=0]
print (b)
     a
1   11
2   12
3   13
5   15
6   16
7   17
9   19
10  20
11  21
13  23
14  24
15  25
17  27
18  28
19  29

<强>详情:

print (np.mod(np.arange(df.index.size),4))
[0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3]

print (np.mod(np.arange(df.index.size),4)!=0)
[False  True  True  True False  True  True  True False  True  True  True
 False  True  True  True False  True  True  True]

如果唯一索引值使用注释中的@jpp解决方案:

b = df.drop(df.index[::4], 0)
相关问题