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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章