将数据从 Pandas 移植到本机 Python 和 Numpy 数据结构中

In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [1.0, 2.0, 3.0], 'C': ['a', 'b', 'c'], 
                       'D': [True, False, True]})

In [2]: df
Out[2]: 
   A    B  C      D
0  1  1.0  a   True
1  2  2.0  b  False
2  3  3.0  c   True

从系列中获取 python 列表:

In [3]: df['A'].tolist()
Out[3]: [1, 2, 3]

DataFrames 没有 tolist() 方法。尝试它会导致 AttributeError:

In [4]: df.tolist()AttributeError                            Traceback (most recent call last)
<ipython-input-4-fc6763af1ff7> in <module>()
----> 1 df.tolist()

//anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name)
   2742             if name in self._info_axis:
   2743                 return self[name]
-> 2744             return object.__getattribute__(self, name)
   2745 
   2746     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'tolist'

从系列中获取一个 numpy 数组:

In [5]: df['B'].values
Out[5]: array([ 1.,  2.,  3.])

你还可以从整个数据帧中获取列数组作为单独的 numpy 数组:

In [6]: df.values
Out[6]: 
array([[1, 1.0, 'a', True],
       [2, 2.0, 'b', False],
       [3, 3.0, 'c', True]], dtype=object)

从系列中获取字典(使用索引作为键):

In [7]: df['C'].to_dict()
Out[7]: {0: 'a', 1: 'b', 2: 'c'}

你还可以将整个 DataFrame 作为字典返回:

In [8]: df.to_dict()
Out[8]: 
{'A': {0: 1, 1: 2, 2: 3},
 'B': {0: 1.0, 1: 2.0, 2: 3.0},
 'C': {0: 'a', 1: 'b', 2: 'c'},
 'D': {0: True, 1: False, 2: True}}

to_dict 方法有一些不同的参数来调整字典的格式。要获取每行的 dicts 列表:

In [9]: df.to_dict('records')
Out[9]: 
[{'A': 1, 'B': 1.0, 'C': 'a', 'D': True},
 {'A': 2, 'B': 2.0, 'C': 'b', 'D': False},
 {'A': 3, 'B': 3.0, 'C': 'c', 'D': True}]

有关创建词典的完整选项列表,请参阅文档