1. 程式人生 > >Python3學習(三十四):python從mongo中取資料,使用pandas.DataFrame進行列操作並轉字典

Python3學習(三十四):python從mongo中取資料,使用pandas.DataFrame進行列操作並轉字典

使用該操作的具體場景(一般與mongo相結合):

比如mongo中存了幾萬條資料,需要將mongo中的資料取出來,並對其中的一列進行相關操作,最後轉化為字典格式。

具體程式碼實現如下:

import pandas as pd
import pymongo
import 你的操作函式

list_tmp = []

#######################  連線mongo資料庫  ###########################
conn = pymongo.Connection('************', xxxx) #裡面是伺服器ip及埠號  
#選擇liao庫,沒有就會自動建立 
db = conn.liao
#使用aoteman集合  
my_set = db['aoteman']

#找出所有去除_id的相關條目,並存為列表
for r in my_set.find({'stock_code':'300033'}, {'_id':0})
    list_tmp.append(r)
data = pd.DataFrame(list_tmp)

#對time_c這一列進行列操作
data['time_c'] = data['time_c'].map(你的操作函式)

#轉換成[{xxx}, {xxxx}, {xxxx}]的格式
result = data.to_dict('records')

另外說一下pandas.DataFrame.to_dict(列操作轉字典)的其它操作

Examples

>>> df = pd.DataFrame({'col1': [1, 2],
...                    'col2': [0.5, 0.75]},
...                   index=['a', 'b'])
>>> df
   col1  col2
a     1   0.50
b     2   0.75
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

You can specify the return orientation.

>>> df.to_dict('series')
{'col1': a    1
         b    2
         Name: col1, dtype: int64,
 'col2': a    0.50
         b    0.75
         Name: col2, dtype: float64}
>>> df.to_dict('split')
{'index': ['a', 'b'], 'columns': ['col1', 'col2'],
 'data': [[1.0, 0.5], [2.0, 0.75]]}
>>> df.to_dict('records')
[{'col1': 1.0, 'col2': 0.5}, {'col1': 2.0, 'col2': 0.75}]
>>> df.to_dict('index')
{'a': {'col1': 1.0, 'col2': 0.5}, 'b': {'col1': 2.0, 'col2': 0.75}}

You can also specify the mapping type.

>>> from collections import OrderedDict, defaultdict
>>> df.to_dict(into=OrderedDict)
OrderedDict([('col1', OrderedDict([('a', 1), ('b', 2)])),
             ('col2', OrderedDict([('a', 0.5), ('b', 0.75)]))])

If you want a defaultdict, you need to initialize it:

>>> dd = defaultdict(list)
>>> df.to_dict('records', into=dd)
[defaultdict(<class 'list'>, {'col1': 1.0, 'col2': 0.5}),
 defaultdict(<class 'list'>, {'col1': 2.0, 'col2': 0.75})]