如何将pandas数据框的第n行提取为pandas数据框? [英] How can I extract the nth row of a pandas data frame as a pandas data frame?

查看:75
本文介绍了如何将pandas数据框的第n行提取为pandas数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 Pandas 数据框如下所示:

X_test.head(4)BoxRatio 推力速度 OnBalRun vwapGain5 -0.163 -0.817 0.741 1.702 0.2188 0.000 0.000 0.732 1.798 0.30711 0.417 -0.298 2.036 4.107 1.79313 0.054 -0.574 1.323 2.553 1.185

如何将第三行(作为 row3)提取为 pd 数据框?换句话说,row3.shape 应该是 (1,5) 而 row3.head() 应该是:

 0.417 -0.298 2.036 4.107 1.793

解决方案

使用带双括号的 .iloc 提取 DataFrame,或使用单括号提取系列.

<预><代码>>>>将熊猫导入为 pd>>>df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})>>>df列 1 列 20 1 31 2 4>>>df.iloc[[1]] # 数据帧结果列 1 列 21 2 4>>>df.iloc[1] # 系列结果列1 2第 2 列 4名称:1,数据类型:int64

扩展到其他形式的 DataFrame 索引,即 .loc.__getitem__():

<预><代码>>>>df.loc[:, ['col2']]列20 31 4>>>df[['col2']]列20 31 4

Suppose a Pandas data frame looks like:

X_test.head(4)
    BoxRatio  Thrust  Velocity  OnBalRun  vwapGain
5     -0.163  -0.817     0.741     1.702     0.218
8      0.000   0.000     0.732     1.798     0.307
11     0.417  -0.298     2.036     4.107     1.793
13     0.054  -0.574     1.323     2.553     1.185

How can I extract the third row (as row3) as a pd data frame? In other words, row3.shape should be (1,5) and row3.head() should be:

 0.417  -0.298     2.036     4.107     1.793

解决方案

Use .iloc with double brackets to extract a DataFrame, or single brackets to pull out a Series.

>>> import pandas as pd
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
>>> df
   col1  col2
0     1     3
1     2     4
>>> df.iloc[[1]]  # DataFrame result
   col1  col2
1     2     4
>>> df.iloc[1]  # Series result
col1    2
col2    4
Name: 1, dtype: int64

This extends to other forms of DataFrame indexing as well, namely .loc and .__getitem__():

>>> df.loc[:, ['col2']]
   col2
0     3
1     4

>>> df[['col2']]
   col2
0     3
1     4

这篇关于如何将pandas数据框的第n行提取为pandas数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆