Pandas - 获取给定列的第一行值

问题描述 投票:190回答:6

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

那么,如何在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
python pandas indexing head
6个回答
315
投票

要选择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.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'

21
投票

请注意,@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

9
投票
  1. df.iloc[0].head(1) - 仅从整个第一行开始的第一个数据集。
  2. df.iloc[0] - 列中的整个第一行。

9
投票

另一种方法:

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)

4
投票

一般来说,如果你想从pandas dataframe中获取J列中的前N行,最好的方法是:

data = dataframe[0:N][:,J]

0
投票

获取保留索引的第一行的另一种方法:

x = df.first('d') # Returns the first day. '3d' gives first three days.

0
投票

例如,从'test'列和第1行ti得到的值就像

df[['test']].values[0][0]

因为只有df[['test']].values[0]回馈阵列

© www.soinside.com 2019 - 2024. All rights reserved.