获取给定列的第一行值

新手上路,请多包涵

这似乎是一个非常简单的问题……但我没有看到我期待的简单答案。

那么,如何在 Pandas 中获取给定列的第 n 行的值? (我对第一行特别感兴趣,但也会对更一般的做法感兴趣)。

例如,假设我想将 Btime 中的 1.2 值作为变量提取。

这样做的正确方法是什么?

 >>> df_test
    ATime   X   Y   Z   Btime  C   D   E
0    1.2  2  15   2    1.2  12  25  12
1    1.4  3  12   1    1.3  13  22  11
2    1.5  1  10   6    1.4  11  20  16
3    1.6  2   9  10    1.7  12  29  12
4    1.9  1   1   9    1.9  11  21  19
5    2.0  0   0   0    2.0   8  10  11
6    2.4  0   0   0    2.4  10  12  15

原文由 Ahmed Haque 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 491
2 个回答

要选择 ith 行, 请使用 iloc

 In [31]: df_test.iloc[0]
Out[31]:
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

要选择 Btime 列中的第 i 个值,您可以使用:

 In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2


df_test['Btime'].iloc[0] (推荐)和 df_test.iloc[0]['Btime'] 之间有区别:

DataFrame 将数据存储在基于列的块中(其中每个块都有一个 dtype)。如果先按列选择,则可以返回 _视图_(这比返回副本更快)并保留原始 dtype。相反,如果您先按行选择,并且如果 DataFrame 具有不同 dtype 的列,则 Pandas 会将数据 复制 到新的 Series of object dtype 中。所以选择列比选择行要快一点。因此,虽然 df_test.iloc[0]['Btime'] 有效,但 df_test['Btime'].iloc[0] 效率更高一些。

在分配方面,两者之间存在很大差异。 df_test['Btime'].iloc[0] = x 影响 df_test ,但 df_test.iloc[0]['Btime'] 可能不会。有关原因的解释,请参见下文。因为索引顺序的细微差别会对行为产生很大影响,所以最好使用单个索引分配:

 df.iloc[0, df.columns.get_loc('Btime')] = x


df.iloc[0, df.columns.get_loc('Btime')] = x (推荐):

为 DataFrame 分配新值的 推荐方法避免链式索引,而是使用 andrew 所示 的方法,

 df.loc[df.index[n], 'Btime'] = x

或者

df.iloc[n, df.columns.get_loc('Btime')] = x

后一种方法要快一些,因为 df.loc 必须将行和列标签转换为位置索引,所以如果您使用 df.iloc ,则需要的转换会少一些。


df['Btime'].iloc[0] = x 有效,但不推荐:

虽然这可行,但它利用了 当前 实现 DataFrame 的方式。无法保证 Pandas 将来必须以这种方式工作。特别是,它利用了(当前) df['Btime'] 总是返回一个视图(不是副本)这样一个事实,所以 df['Btime'].iloc[n] = x 可以用于在第 n 个位置 分配 一个新值的 Btime df 列。

由于 Pandas 没有明确保证索引器何时返回视图和副本,因此使用链式索引的赋值通常总是引发 SettingWithCopyWarning 即使在这种情况下赋值成功修改了 df

 In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

In [26]: df
Out[26]:
  foo  bar
0   A   99  <-- assignment succeeded
2   B  100
1   C  100


df.iloc[0]['Btime'] = x 不起作用:

相反,使用 df.iloc[0]['bar'] = 123 的分配不起作用,因为 df.iloc[0] 正在返回一个副本:

 In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df
Out[67]:
  foo  bar
0   A   99  <-- assignment failed
2   B  100
1   C  100


警告:我之前曾建议 df_test.ix[i, 'Btime'] 。但这不能保证给您 ith 值,因为 ix 在尝试按 位置 索引之前尝试按 标签 索引。因此,如果 DataFrame 的整数索引不是从 0 开始的排序顺序,那么使用 ix[i] 将返回 标记为 i 的行,而不是 ith .例如,

 In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]:
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'

原文由 unutbu 发布,翻译遵循 CC BY-SA 4.0 许可协议

请注意,@unutbu 的答案将是正确的,直到您想将值设置为新的值,然后如果您的数据框是视图,它将不起作用。

 In [4]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [5]: df['bar'] = 100
In [6]: df['bar'].iloc[0] = 99
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.16.0_19_g8d2818e-py2.7-macosx-10.9-x86_64.egg/pandas/core/indexing.py:118: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

另一种始终适用于设置和获取的方法是:

 In [7]: df.loc[df.index[0], 'foo']
Out[7]: 'A'
In [8]: df.loc[df.index[0], 'bar'] = 99
In [9]: df
Out[9]:
  foo  bar
0   A   99
2   B  100
1   C  100

原文由 andrew 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题