pandas 从 DataFrame 的最后一行获取列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46221671/
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
Get list from last row of DataFrame
提问by steff
I have a DataFrame looking like this:
我有一个如下所示的 DataFrame:
28 91 182
Date
2017-09-07 0.97 1.05 1.15
2017-09-08 0.95 1.04 1.14
2017-09-11 0.96 1.06 1.16
2017-09-12 0.99 1.04 1.16
2017-09-13 0.99 1.04 1.16
From this DataFrame i would like to get a list of the values of the last row.
从这个 DataFrame 我想得到最后一行的值的列表。
[0.99, 1.04, 1.16]
I attempted to use
我试图使用
np.array(tbill.iloc[-1:].values).tolist()
which returns
返回
[[0.99, 1.04, 1.16]]
but feels overly complicated.
但感觉过于复杂。
Is there a more simple way to do this?
有没有更简单的方法来做到这一点?
回答by miradulo
Just slice the underlying array.
只需对底层数组进行切片。
df.values[-1].tolist()
which yields
这产生
[0.99, 1.04, 1.16]
回答by Brad Solomon
Or just:
要不就:
df.iloc[-1].tolist()
Example:
例子:
df = pd.DataFrame(np.random.randn(10,3))
print(df.iloc[-1].tolist())
[-0.3000246004134489, -0.3626924316159151, 0.9523820239889618]
@miradulo's solutionwill actually be faster in this case, I believe because indexing a NumPy array is significantly faster than indexing a DataFrame.
在这种情况下,@miradulo 的解决方案实际上会更快,我相信因为索引 NumPy 数组比索引 DataFrame 快得多。
回答by Tai
There is a function called tail
that you can access rows backward.
有一个函数被调用tail
,您可以向后访问行。
df.tail(1).values.tolist() # get last row and its values
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.tail.html
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.tail.html