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})]

猜你喜欢

转载自blog.csdn.net/liao392781/article/details/82836284
今日推荐