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

CBr*_*uer 7 python python-3.x pandas

假设Pandas数据框如下所示:

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
Run Code Online (Sandbox Code Playgroud)

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

 0.417  -0.298     2.036     4.107     1.793
Run Code Online (Sandbox Code Playgroud)

Bra*_*mon 20

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

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • 关于 pandas,我最喜欢的一点是常见问题的解决方案是如此易于发现且合乎逻辑。 (2认同)