将python数据帧转换为列表

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

convert python dataframe to list

pythonpython-3.xpython-2.7pandas

提问by user1452849

I have a Python dataFrame with multiple columns.

我有一个包含多列的 Python 数据框。

  LogBlk    Page                                    BayFail       
  0          0                                 [0, 1, 8, 9]  
  1          16           [0, 1, 4, 5, 6, 8, 9, 12, 13, 14]  
  2          32           [0, 1, 4, 5, 6, 8, 9, 12, 13, 14]  
  3          48           [0, 1, 4, 5, 6, 8, 9, 12, 13, 14]  

I want to find BayFails that is associated with LogBlk=0, and Page=0.

我想找到与 LogBlk=0 和 Page=0 关联的 BayFails。

df2 = df[ (df['Page'] == 16) & (df['LogBlk'] == 0) ]['BayFail']

This will return [0,1,8,9]

这将返回 [0,1,8,9]

What I want to do is to convert this pandas.series into a list. Does anyone know how to do that?

我想要做的是将这个 pandas.series 转换成一个列表。有谁知道这是怎么做到的吗?

回答by unutbu

pandas.Series, has a tolistmethod:

pandas.Series,有一个tolist方法

In [10]: import pandas as pd

In [11]: s = pd.Series([0,1,8,9], name = 'BayFail')

In [12]: s.tolist()
Out[12]: [0L, 1L, 8L, 9L]


Technical note: In my original answer I said that Serieswas a subclass of numpy.ndarrayand inherited its tolistmethod. While that's true for Pandas version 0.12 or older, In the soon-to-be-released Pandas version 0.13, Serieshas been refactored to be a subclass of NDFrame. Seriesstill has a tolistmethod, but it has no direct relationship to the numpy.ndarraymethod of the same name.

技术说明:在我最初的回答中,我说这Series是一个子类numpy.ndarray并继承了它的tolist方法。虽然这对于 Pandas 0.12 或更早版本是正确的,但在即将发布的 Pandas 0.13 版本中,Series已被重构为NDFrame. Series仍然有一个tolist方法,但它numpy.ndarray与同名方法没有直接关系。

回答by unutbu

You can also convert them to numpy arrays

您也可以将它们转换为 numpy arrays

In [124]: s = pd.Series([0,1,8,9], name='BayFail')

In [125]: a = pd.np.array(s)
Out[125]: array([0, 1, 8, 9], dtype=int64)

In [126]: a[0]
Out[126]: 0