Python 获取没有索引的数据框列的最后一个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34166030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
obtaining last value of dataframe column without index
提问by laszlopanaflex
Suppose I have a DataFrame such as:
假设我有一个 DataFrame,例如:
df = pd.DataFrame(np.random.randn(10,5), columns = ['a','b','c','d','e'])
and I would like to retrieve the last value in column e. I could do:
我想检索 e 列中的最后一个值。我可以:
df['e'].tail(1)
but this would return a series which has index 9 with it. ideally, i just want to obtain the value as a number i can work with directly. i could also do:
但这将返回一个索引为 9 的系列。理想情况下,我只想获得可以直接使用的数字的值。我也可以这样做:
np.array(df['e'].tail(1))
but this would then require me to access/call the 0'th element of it before i can really work with it. is there a a more direct/easy way to do this?
但这将要求我在真正使用它之前访问/调用它的第 0 个元素。有没有更直接/更简单的方法来做到这一点?
采纳答案by Anton Protopopov
You could try iloc
method of dataframe:
您可以尝试iloc
数据框的方法:
In [26]: df
Out[26]:
a b c d e
0 -1.079547 -0.722903 0.457495 -0.687271 -0.787058
1 1.326133 1.359255 -0.964076 -1.280502 1.460792
2 0.479599 -1.465210 -0.058247 -0.984733 -0.348068
3 -0.608238 -1.238068 -0.126889 0.572662 -1.489641
4 -1.533707 -0.218298 -0.877619 0.679370 0.485987
5 -0.864651 -0.180165 -0.528939 0.270885 1.313946
6 0.747612 -1.206509 0.616815 -1.758354 -0.158203
7 -2.309582 -0.739730 -0.004303 0.125640 -0.973230
8 1.735822 -0.750698 1.225104 0.431583 -1.483274
9 -0.374557 -1.132354 0.875028 0.032615 -1.131971
In [27]: df['e'].iloc[-1]
Out[27]: -1.1319705662711321
Or if you want just scalar you could use iat
which is faster. From docs:
If you only want to access a scalar value, the fastest way is to use the
at
andiat
methods, which are implemented on all of the data structures
如果只想访问标量值,最快的方法是使用
at
和iat
方法,它们在所有数据结构上都实现
In [28]: df.e.iat[-1]
Out[28]: -1.1319705662711321
Benchmarking:
基准测试:
In [31]: %timeit df.e.iat[-1]
100000 loops, best of 3: 18 μs per loop
In [32]: %timeit df.e.iloc[-1]
10000 loops, best of 3: 24 μs per loop