如何将 Pandas 数据帧的第 n 行作为 Pandas 数据帧进行提取?

47
假设一个Pandas数据框如下所示:
    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

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

 0.417  -0.298     2.036     4.107     1.793

1
你看过这个链接吗?https://dev59.com/omQo5IYBdhLWcg3wZehg - Zero
实际上,Zero已经找到了详细的适当答案。 - bellum
可能是Pandas按整数索引选择数据帧行的重复问题。 - bellum
3个回答

80
使用双括号与.iloc一起提取DataFrame,或使用单括号提取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

这同样适用于其他形式的 DataFrame 索引,即 .loc 和 __getitem__():此 扩展到其他形式的 DataFrame 索引
>>> df.loc[:, ['col2']]
   col2
0     3
1     4

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

3
我最喜欢大熊猫的一点是,它们在解决常见问题时的方法非常易于发现和合乎逻辑。 - Brandon Kuczenski

3

或者您也可以使用 take

In [4]: df.take([2])
Out[4]: 
    BoxRatio  Thrust  Velocity  OnBalRun  vwapGain
11     0.417  -0.298     2.036     4.107     1.793

0

你也可以对数据框进行切片。例如,要将第三行作为数据框获取,请使用切片2:3

row3 = df.iloc[2:3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接