获取指定列的第一行值
这个问题看起来简单得不可思议……但我没有找到我期待的简单答案。
那么,我该如何在Pandas中获取某一列的第n行的值呢?(我特别想知道第一行的值,但也想了解更一般的方法)。
举个例子,假设我想把
这样做的正确方法是什么呢?
>>> 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
10 个回答
一般来说,如果你想从一个叫做 pandas dataframe
的数据表中,提取出第 N 行 的第 J 列 的数据,最好的方法是:
data = dataframe[0:N][:,J]
1. df.iloc[0].head(1)
- 这个代码的意思是从整个第一行中只取出第一个数据。
2. df.iloc[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
还有一种方法可以做到这一点:
first_value = df['Btime'].values[0]
这种方法似乎比使用 .iloc
更快:
In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
要选择第 i
行,可以使用 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)是以列为基础来存储数据的(每一列的数据类型是相同的)。如果你先按列选择,可能会返回一个 视图(比返回一个副本要快),并且原来的数据类型会被保留。相反,如果你先按行选择,并且数据框中有不同数据类型的列,那么 Pandas 会把数据复制到一个新的对象类型的序列中。因此,选择列比选择行要快一点。所以,虽然 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
(推荐):
给数据框赋新值的推荐方法是避免链式索引,而是使用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
可以用,但不推荐:
虽然这样可以用,但这是利用了数据框当前的实现方式。未来 Pandas 不一定会这样工作。特别是,它利用了当前 df['Btime']
总是返回一个视图(而不是副本)的事实,因此 df['Btime'].iloc[n] = x
可以用来赋值到 df
的 Btime
列的第 n
个位置。
由于 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']
。但这并不能保证你得到的是第 i
个值,因为 ix
会先尝试按标签索引,再按位置索引。所以如果数据框的整数索引不是从 0 开始的有序排列,使用 ix[i]
会返回标签为 i
的行,而不是第 i
行。例如,
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'