Python 获取 Pandas DataFrame 的行索引值作为列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18358938/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:33:17  来源:igfitidea点击:

Get row-index values of Pandas DataFrame as list?

pythonlistpandasindexing

提问by TravisVOX

I'm probably using poor search terms when trying to find this answer. Right now, before indexing a DataFrame, I'm getting a list of values in a column this way...

我在试图找到这个答案时可能使用了糟糕的搜索词。现在,在索引 DataFrame 之前,我以这种方式获取列中的值列表......

 list = list(df['column']) 

...then I'll set_indexon the column. This seems like a wasted step. When trying the above on an index, I get a key error.

...那我set_index就上专栏了。这似乎是一个浪费的步骤。在索引上尝试上述操作时,出现关键错误。

How can I grab the values in an index (both single and multi) and put them in a list or a list of tuples?

如何获取索引(单个和多个)中的值并将它们放入列表或元组列表中?

采纳答案by Phillip Cloud

To get the indexvalues as a list/listof tuples for Index/MultiIndexdo:

为了得到index值作为list/listtupleS代表Index/MultiIndex做到:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

或者

list(df.index.values)  # this will always work in pandas

回答by smci

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

如果您只是让这些手动传递到df.set_index(),那是不必要的。直接做df.set_index['your_col_name', drop=False],已经。

It's very rare in pandas that you need to get an index as a Python list (unless you;re doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

在 Pandas 中,很少需要将索引作为 Python 列表获取(除非你正在做一些非常时髦的事情,或者将它们传递回 NumPy),所以如果你经常这样做,这是一种代码气味你做错了什么。