Pandas - 获取给定列的第一行值 [英] Pandas - Get first row value of a given column
问题描述
这似乎是一个非常简单的问题...但我没有看到我期待的简单答案。
This seems like a ridiculously easy question... but I'm not seeing the easy answer I was expecting.
那么,我如何获得价值Pandas中给定列的第n行? (我对第一行特别感兴趣,但也会对更普遍的做法感兴趣)。
So, how do I get the value at an nth row of a given column in Pandas? (I am particularly interested in the first row, but would be interested in a more general practice as well).
例如,假设我想拉1.2值在Btime中作为变量。
For example, let's say I want to pull the 1.2 value in Btime as a variable.
这是正确的方法吗?
df_test =
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
行,使用 iloc
:
To select the ith
row, 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
选择第i个您可以使用的 Btime
列中的值:
To select the ith value in the Btime
column you could use:
In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2
警告:我之前曾建议 df_test.ix [i,'Btime']
。但是这不能保证给你 ith
值,因为 ix
尝试按 label 在尝试按位置进行索引之前。因此,如果DataFrame的整数索引不是从0开始的排序顺序,那么使用 ix [i]
将返回标记为 <的行code> i 而不是 ith
行。例如,
Warning: I had previously suggested df_test.ix[i, 'Btime']
. But this is not guaranteed to give you the ith
value since ix
tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i]
will return the row labeled i
rather than the ith
row. For example,
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'
这篇关于Pandas - 获取给定列的第一行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!