码迷,mamicode.com
首页 > 其他好文 > 详细

pandas基础操作

时间:2017-06-20 21:05:32      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:pandas

import pandas as pd

1、定义一个字典

data = {‘sales_volume‘: [100, 123, 446, 233, 456], ‘month‘: [‘1月‘, ‘2月‘, ‘3月‘, ‘4月‘, ‘5月‘]

        , ‘product_id‘: [‘1112‘, ‘1113‘, ‘1114‘,‘1115‘,‘1116‘], ‘color‘:[‘red‘, ‘red‘, ‘black‘, ‘green‘, ‘black‘]}

2、将字典放入dataframe数据结构,自动生成一列数据做索引0-4

df = DataFrame(data)

print df

   color month product_id  sales_volume

0    red    1月       1112           100

1    red    2月       1113           123

2  black    3月       1114           446

3  green    4月       1115           233

4  black    5月       1116           456


3、将dataframe数据处理为字典格式

keys = list(df.keys())

values = df.values

print keys,values

dicts = [dict(zip(keys, value)) for value in values]

print dicts

[{‘color‘: ‘red‘, ‘sales_volume‘: 100L, ‘product_id‘: ‘1112‘, ‘month‘: ‘1\xe6\x9c\x88‘}, {‘color‘: ‘red‘, ‘sales_volume‘: 123L, ‘product_id‘: ‘1113‘, ‘month‘: ‘2\xe6\x9c\x88‘}, {‘color‘: ‘black‘, ‘sales_volume‘: 446L, ‘product_id‘: ‘1114‘, ‘month‘: ‘3\xe6\x9c\x88‘}, {‘color‘: ‘green‘, ‘sales_volume‘: 233L, ‘product_id‘: ‘1115‘, ‘month‘: ‘4\xe6\x9c\x88‘}, {‘color‘: ‘black‘, ‘sales_volume‘: 456L, ‘product_id‘: ‘1116‘, ‘month‘: ‘5\xe6\x9c\x88‘}]


4、通过groupy计算和,精确到color

print df.groupby([‘product_id‘, ‘color‘]).sum()

                  

product_id color    sales_volume            

1112       red              223

1113       black           446

               green          233

1116       black           456


pandas基础操作

标签:pandas

原文地址:http://linuxnewstar.blog.51cto.com/6967359/1940269

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!