【问题标题】:How can I extract the nth row of a pandas data frame as a pandas data frame?如何将熊猫数据框的第 n 行提取为熊猫数据框?
【发布时间】:2018-02-28 15:43:27
【问题描述】:

假设 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

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

使用带双括号的.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

这个extends to other forms of DataFrame indexing也是如此,即.loc和.__getitem__():

>>> df.loc[:, ['col2']]
   col2
0     3
1     4

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

【讨论】:

  • 我最喜欢 pandas 的一点是常见问题的解决方案如此易于发现和合乎逻辑。
猜你喜欢
  • 2021-05-25
  • 2014-10-03
  • 2021-11-11
  • 1970-01-01
  • 2018-04-15
  • 2023-04-02
  • 2019-03-24
  • 2021-11-09
相关资源
最近更新 更多