这似乎是一个非常简单的问题......但我没有看到我期待的简单答案。
那么,如何在 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
最佳答案
要选择 ith 行,use
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']
有区别:DataFrames 将数据存储在基于列的 block 中(其中每个 block 都有一个
dtype)。如果先按列选择,则可以返回 view(即
比返回副本更快)并保留原始数据类型。相比之下,
如果您首先按行选择,并且 DataFrame 具有不同的列
dtypes,然后 Pandas 将数据复制到一个新的对象 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
(推荐):recommended way 将新值分配给 DataFrame 到 avoid chained indexing , 而是使用方法 shown by 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
可用于分配一个新值
在 df
的 Btime
列的第 n 个位置。
由于 Pandas 没有明确保证索引器何时返回 View 和副本,因此使用链式索引的赋值通常总是引发 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
在尝试按 position索引之前尝试按 label 进行索引时间>。因此,如果 DataFrame 有一个从 0 开始没有按排序顺序排列的整数索引,那么使用 ix[i]
将返回行 labeled 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'
https://stackoverflow.com/questions/25254016/