[英]How can I extract the nth row of a pandas data frame as a pandas data frame?
假设 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
如何将第三行(作为 row3)提取为 pd 数据框? 换句话说, row3.shape 应该是 (1,5) 而 row3.head() 应该是:
0.417 -0.298 2.036 4.107 1.793
使用带有双括号的.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
这也扩展到其他形式的 DataFrame 索引,即.loc
和.__getitem__()
:
>>> df.loc[:, ['col2']]
col2
0 3
1 4
>>> df[['col2']]
col2
0 3
1 4
或者,您也可以使用take
:
In [4]: df.take([2])
Out[4]:
BoxRatio Thrust Velocity OnBalRun vwapGain
11 0.417 -0.298 2.036 4.107 1.793
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.