chart-7

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Feb 21 15:17:51 2017
  4. @author: zzpp220
  5. """
  6. '''合并(merge)-列或者连接(concat)-行数据集'''
  7. from pandas import DataFrame,Series
  8. from numpy import nan as NaN
  9. import pandas as pd
  10. import numpy as np
  11. import json
  12. df1=DataFrame({'left':list('bbacaab'),'data1':range(7)})
  13. df2=DataFrame({'right':list('abd'),'data2':range(3)})
  14. df12=pd.merge(df1,df2,left_on='left',right_on='right') ##分为内、外连接、像mysql 一样
  15. ##重塑和轴向旋转 stack: change col to row 和unstack:change row to col
  16. '''这个好!!该有的都由了'''
  17. df3=DataFrame(np.arange(6).reshape((2,3)),index=pd.Index(['sd','gz'],name='state'),columns=pd.Index(['one','two','thr'],name='number'))
  18. '''多重索引的Series和DataFrame可以通过stack,unstack相互转哈,默认情况下取的都是最内层的索引'''
  19. ##将列转为行,得到一个Series,索引是一个多重索引
  20. stack_df3=df3.stack()
  21. #对于一个层次化索引的Series ,可以用unstack 重排为DataFrame。
  22. stack_df3.unstack()
  23. '''
  24. df3.stack()
  25. Out[19]:
  26. state  number
  27. sd     one       0
  28.       two       1
  29.       thr       2
  30. gz     one       3
  31.       two       4
  32.       thr       5
  33. dtype: int64
  34. stack_df3.unstack()
  35. Out[22]:
  36. number  one  two  thr
  37. state                
  38. sd        0    1    2
  39. gz        3    4    5
  40. unstack and stack operate on the in-most level-index,also can operate on other level when give other para
  41. '''
  42. stack_df3.unstack('state')==stack_df3.unstack(0)## operate on the out-most level the same as :
  43. ''''stack_df3.unstack() 默认是按最内层也就是’number‘
  44. Out[22]:
  45. number  one  two  thr
  46. state                
  47. sd        0    1    2
  48. gz        3    4    5
  49.                    stack_df3.unstack('state')==stack_df3.unstack(0)
  50.                    Out[25]:
  51.                    state     sd    gz
  52.                    number            
  53.                    one     True  True
  54.                    two     True  True
  55.                    thr     True  True
  56. '''
  57. '''对全部的营养数据做分析'''
  58. db=json.load(open('/media/zzpp220/Data/Linux_Documents/DOWNLOAD/python-DataAnalysis/pydata-book-master/ch07/foods-2011-10-03.json'))
  59. nutrients=DataFrame(db[0]['nutrients'])
  60. '''
  61. nutrients[:10]
  62. Out[36]:
  63.                   description        group units    value
  64. 0                      Protein  Composition     g    25.18
  65. 1            Total lipid (fat)  Composition     g    29.20
  66. 2  Carbohydrate, by difference  Composition     g     3.06
  67. 3                          Ash        Other     g     3.28
  68. 4                       Energy       Energy  kcal   376.00
  69. 5                        Water  Composition     g    39.28
  70. 6                       Energy       Energy    kJ  1573.00
  71. 7         Fiber, total dietary  Composition     g     0.00
  72. 8                  Calcium, Ca     Elements    mg   673.00
  73. 9                     Iron, Fe     Elements    mg     0.64
  74. '''
  75. info_keys=['description','group','id','manufacturer']
  76. info=DataFrame(db,columns=info_keys)##仅仅导入db中的info_keys中的字段,其他的就不导入了; 
  77. info[:5]
  78. '''查看食物类别的分布情况'''
  79. #info.group.value_counts()[:10]#查看group中的分布情况==pd.values_count(info.group)
  80. '''将所有的食物的营养成分整合到一个大表中'''
  81. nutrients=[]
  82. for rec in db:
  83.    fnuts=DataFrame(rec['nutrients'])##将各食物的营养成分整合到一个大表
  84.    fnuts['id']=rec['id']#并且在表中添加一个表示编号的列,用原来的表中的值赋值
  85.    nutrients.append(fnuts)#依次将DataFrame添加到大的list中
  86. nutrients=pd.concat(nutrients,ignore_index=True)##用concat连接起来大表
  87. '''查看表中有多少重复项'''
  88. nutrients.duplicated().sum()
  89. '''丢弃重复项'''
  90. nutrients.drop_duplicates()
  91. '''重命名对象中的列名(因为二者有相同的列,可能会混淆)'''
  92. col_mapping={'description':'food','group':'fgroup'}
  93. info=info.rename(columns=col_mapping,copy=False)
  94. '''
  95. info.rename(columns=col_mapping,copy=False)[:3]
  96. Out[50]:
  97.              food                  fgroup    id manufacturer
  98. 0  Cheese, caraway  Dairy and Egg Products  1008            
  99. 1  Cheese, cheddar  Dairy and Egg Products  1009            
  100. 2     Cheese, edam  Dairy and Egg Products  1018
  101. '''
  102. col_mapping={'description':'nutrients','group':'nutgroup'}
  103. nutrients=nutrients.rename(columns=col_mapping,copy=False)
  104. '''合并info和nutrients'''
  105. ndata=pd.merge(nutrients,info,on='id',how='outer')
  106. '''根据营养分类,得出锌的中位值'''
  107. result=ndata.groupby(['nutrients','fgroup'])['value'].quantile(0.5)


原文地址:https://www.cnblogs.com/zzxx-myblog/p/6481284.html