Python 如何将pandas数据框的第n行提取为pandas数据框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46307490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I extract the nth row of a pandas data frame as a pandas data frame?
提问by CBrauer
Suppose a Pandas data frame looks like:
假设 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
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:
如何将第三行(作为 row3)提取为 pd 数据框?换句话说, row3.shape 应该是 (1,5) 而 row3.head() 应该是:
0.417 -0.298 2.036 4.107 1.793
回答by Brad Solomon
Use .iloc
with double brackets to extract a DataFrame, or single brackets to pull out a Series.
使用.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
This extends to other forms of DataFrame indexingas well, namely .loc
and .__getitem__()
:
这也扩展到其他形式的 DataFrame 索引,即.loc
和.__getitem__()
:
>>> df.loc[:, ['col2']]
col2
0 3
1 4
>>> df[['col2']]
col2
0 3
1 4