我需要检查df.head()和df.tail()很多次。当使用df.head(), df.tail() jupyter笔记本时,消除了难看的输出。
是否有任何单行命令,以便我们只能选择前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])]]发布于 2019-04-16 01:58:32
试着看看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发布于 2019-04-16 02:02:03
df.query("index<5 | index>"+str(len(df)-5))
这里有一种查询索引的方法。您可以将这些值更改为您想要的任何值。
发布于 2019-04-16 02:06:44
另一种方法(按this方式发布)
.isin()生成一些虚拟/演示数据
df = pd.DataFrame({'a':range(10,100)})
print(df.head())
a
0 10
1 11
2 12
3 13
4 14
print(df.tail())
a
85 95
86 96
87 97
88 98
89 99
print(df.shape)
(90, 1)生成所需索引的列表
ls = list(range(5)) + list(range(len(df)-5, len(df)))
print(ls)
[0, 1, 2, 3, 4, 85, 86, 87, 88, 89]使用索引列表对DataFrame切片
df_first_last_5 = df[df.index.isin(ls)]
print(df_first_last_5)
a
0 10
1 11
2 12
3 13
4 14
85 95
86 96
87 97
88 98
89 99https://stackoverflow.com/questions/55699481
复制相似问题