python - 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])]]
解决方案
试试看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
推荐阅读
- javascript - 如何在 typescript 和 webpack 4 中使用 Snap.svg 插件 (Snap.svg.zpd)
- jquery - 创建一个超出浏览器窗口的下拉菜单
- java - 从目录中读取所有文件和嵌套文件时,线程“main”java.lang.StackOverflowError 中的异常
- python - matplot lib轴混淆将字符串映射到轴
- beautifulsoup - 使用 Beautifulsoup 获取文本
- azure - 我应该如何在 Linux Mint 18.3 上安装 Azure 存储资源管理器?
- kubernetes - 启动 Kubernetes minikube 集群时出错
- c - 将输入文件分成两个不同的二维数组
- laravel - Laravel 材质组件
- node.js - Node Twitter bot 在 Heroku 上不断崩溃