How can I extract the nth row of a pandas data frame as a pandas data frame?

前端 未结 1 511
暖寄归人
暖寄归人 2021-02-12 10:49

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            


        
相关标签:
1条回答
  • 2021-02-12 11:23

    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
    
    0 讨论(0)
提交回复
热议问题