首页 > 解决方案 > Pandas 单个 iloc 操作中的前 5 行和后 5 行

问题描述

我需要检查很多次df.head()df.tail()使用df.head(), df.tail()jupyter notebook 时会显示丑陋的输出。

是否有任何单行命令,以便我们只能选择前 5 行和后 5 行:

就像是:
df.iloc[:5 | -5:] ?

测试示例:

df = pd.DataFrame(np.random.rand(20,2))
df.iloc[:5]

更新
丑陋但有效的方法:

df.iloc[(np.where( (df.index < 5) | (df.index > len(df)-5)))[0]]

or,
df.iloc[np.r_[np.arange(5), np.arange(df.shape[0]-5, df.shape[0])]]

标签: pythonpandas

解决方案


试试看numpy.r_

df.iloc[np.r_[0:5, -5:0]]
Out[358]: 
           0         1
0   0.899673  0.584707
1   0.443328  0.126370
2   0.203212  0.206542
3   0.562156  0.401226
4   0.085070  0.206960
15  0.082846  0.548997
16  0.435308  0.669673
17  0.426955  0.030303
18  0.327725  0.340572
19  0.250246  0.162993

head+tail也不是一个坏的解决方案

df.head(5).append(df.tail(5))
Out[362]: 
           0         1
0   0.899673  0.584707
1   0.443328  0.126370
2   0.203212  0.206542
3   0.562156  0.401226
4   0.085070  0.206960
15  0.082846  0.548997
16  0.435308  0.669673
17  0.426955  0.030303
18  0.327725  0.340572
19  0.250246  0.162993

推荐阅读