char-8

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Feb 21 22:07:13 2017
  4. @author: zzpp220
  5. """
  6. from pandas import DataFrame,Series
  7. from numpy import nan as NaN
  8. import pandas as pd
  9. import numpy as np
  10. df=DataFrame({'k1':list('aabba'),'k2':['one','two','one','two','one'],'data1':np.random.randn(5),'data2':np.random.randn(5)})
  11. #分组键为Series对象
  12. grouped=df.groupby('k1')
  13. desc_group=grouped.describe()
  14. grouped_1=df['data1'].groupby([df['k1'],df['k2']]).sum()##group 是一个series对象
  15. ## 有多重索引的Series和DataFrame中的相互转变
  16. ##分组键为groupby前面对象中的列名
  17. df.groupby(['k1','k2']).sum().unstack()
  18. df.groupby(['k1','k2']).sum().unstack().stack([0,1])
  19. ##粉组件是任何长度适当的数组
  20. states=np.array(['sd','gd','sd','fj','fj'])
  21. year=np.array([2005,2006,2005,2005,2006])
  22. df.groupby([states,year]).mean()
  23. ##GroupBy 对象的数据聚合 按照不同的的聚合函数聚合
  24. tips=pd.read_csv('/media/zzpp220/Data/Linux_Documents/DOWNLOAD/python-DataAnalysis/pydata-book-master/ch08/tips.csv')
  25. tips['tip_pct']=tips['tip']/tips['total_bill']
  26. gro_tips=tips.groupby(['sex','smoker'])
  27. #对聚合后的1列应用1个聚合函数:
  28. gro_tips['tip_pct'].mean()
  29. gro_tips['tip_pct'].agg('mean')##同上,只不过是把函数名用字符串的形似传入
  30. #对聚合后的1列应用多个聚合函数:
  31. gro_tips['tip_pct'].agg(['mean','std','var'])##传入一组函数名,得到DataFrame的列就会以相应的函数命名
  32. gro_tips['tip_pct'].agg([('avg','mean'),('vag','std'),('gav','var')])#按照(name.funciton)传入二元元祖列表,返回的表的各列名是元祖第一个元素
  33. '''
  34. gro_tips['tip_pct'].mean()
  35. Out[94]:
  36. sex     smoker
  37. Female  No        0.156921
  38.        Yes       0.182150
  39. Male    No        0.160669
  40.        Yes       0.152771
  41. Name: tip_pct, dtype: float64
  42. gro_tips['tip_pct'].agg(['mean','std','var'])
  43. Out[98]:
  44.                   mean       std       var
  45. sex    smoker                              
  46. Female No      0.156921  0.036421  0.001327
  47.       Yes     0.182150  0.071595  0.005126
  48. Male   No      0.160669  0.041849  0.001751
  49.       Yes     0.152771  0.090588  0.008206
  50. gro_tips['tip_pct'].agg([('avg','mean'),('vag','std'),('gav','var')])
  51. Out[99]:
  52.                    avg       vag       gav
  53. sex    smoker                              
  54. Female No      0.156921  0.036421  0.001327
  55.       Yes     0.182150  0.071595  0.005126
  56. Male   No      0.160669  0.041849  0.001751
  57.       Yes     0.152771  0.090588  0.008206
  58. '''
  59. ##设计对表中的多个列应用同样的多个函数
  60. ## 对'tip_pct','total_bill' 分别计算functions中的三个统计信息
  61. functions=['count','mean','max']
  62. asix=[('name1','count'),('name2','mean'),('name3','max')]
  63. result=gro_tips['tip_pct','total_bill'].agg(functions)
  64. asix_result=gro_tips['tip_pct','total_bill'].agg(asix)
  65. '''
  66. result
  67. Out[102]:
  68.              tip_pct                     total_bill                  
  69.                count      mean       max      count       mean    max
  70. sex    smoker                                                        
  71. Female No          54  0.156921  0.252672         54  18.105185  35.83
  72.       Yes         33  0.182150  0.416667         33  17.977879  44.30
  73. Male   No          97  0.160669  0.291990         97  19.791237  48.33
  74.       Yes         60  0.152771  0.710345         60  22.284500  50.81
  75.      
  76.      
  77. asix_result
  78. Out[105]:
  79.              tip_pct                     total_bill                  
  80.                name1     name2     name3      name1      name2  name3
  81. sex    smoker                                                        
  82. Female No          54  0.156921  0.252672         54  18.105185  35.83
  83.       Yes         33  0.182150  0.416667         33  17.977879  44.30
  84. Male   No          97  0.160669  0.291990         97  19.791237  48.33
  85.       Yes         60  0.152771  0.710345         60  22.284500  50.81      
  86.      
  87.       如上表,result拥有层次化的列,这相当于对各列应用不同的聚合函数后,再分别进行聚合,然后用concat进行聚合。
  88. '''
  89. ##`对多个不同的列应用不同的函数,传入列名和带应用函数名的字典
  90. map={'tip_pct':['min','max','mean','std'],'size':'sum',}
  91. diff_to_diff=gro_tips.agg(map)
  92. ''' diff_to_diff
  93. Out[109]:
  94.                tip_pct                               size
  95.                    min       max      mean       std  sum
  96. sex    smoker                                            
  97. Female No      0.056797  0.252672  0.156921  0.036421  140
  98.       Yes     0.056433  0.416667  0.182150  0.071595   74
  99. Male   No      0.071804  0.291990  0.160669  0.041849  263
  100.       Yes     0.035638  0.710345  0.152771  0.090588  150
  101. '''
  102. #-------------apply 函数,返回一个pandas对象或者标量值-----------------------------------
  103. '''定义函数得到表df按照列名为column的升序排序后的结果,选出最大5个tip_pct所在的行‘'''
  104. def top(df,n=5,column='tip_pct'):#按照
  105.    return df.sort_index(by=column)[-n:]
  106.    
  107. top_col=top(tips,n=6)
  108. tips.groupby('smoker').apply(top,n=3)##返回一个层次化索引的dataframe
  109. tips.groupby('smoker')['tip_pct'].describe().unstack(0)
  110. test2=DataFrame(np.arange(24).reshape(6,4),index=['row_1', 'row_2', 'row_3', 'row_4', 'row_5', 'row_6'],columns=['col_1','col_2','col_3', 'col_4'])
  111. test2['smoker']=Series(['no','yes','no','yes','yes','yes'],index=['row_1', 'row_2', 'row_3', 'row_4', 'row_5', 'row_6'])
  112. test2=test2.rename_axis({'col_1':'tip_pct'},axis=1)
  113. test2['tip_pct']=[2,5,4,1,2,6]#
  114. test2['col_2']=[7,8,5,-1,4,6]
  115. test2.groupby('smoker').apply(top,n=3)##在groupby对象上调用apply,返回一个层次化索引的dataframe
  116. test2.groupby('smoker').apply(top,n=3).unstack()
  117. ##如果不想要层次化的索引,可以把分组键禁止掉
  118. test2.groupby('smoker',group_keys=False).apply(top,n=3)
  119. '''
  120. 将tips按找smoker分组,对于每一个组内都应用top 函数,应用完成后,将各个组的应用结果concat起来
  121. 返回的结果就有了一个层次化的索引,内层的索引就是tip中原来的 索引值
  122. total_bill   tip     sex smoker   day    time  size   tip_pct
  123. smoker                                                                  
  124. No     51        10.29  2.60  Female     No   Sun  Dinner     2  0.252672
  125.       149        7.51  2.00    Male     No  Thur   Lunch     2  0.266312
  126.       232       11.61  3.39    Male     No   Sat  Dinner     2  0.291990
  127. -------------------------------------------------------------------------------concat---------------
  128. Yes    67         3.07  1.00  Female    Yes   Sat  Dinner     1  0.325733
  129.       178        9.60  4.00  Female    Yes   Sun  Dinner     2  0.416667
  130.       172        7.25  5.15    Male    Yes   Sun  Dinner     2  0.710345
  131.      
  132. test2.groupby('smoker').apply(top,n=3):
  133. tip_pct  col_2  col_3  col_4 smoker
  134. smoker                                          
  135. no     row_1        2      7      2      3     no
  136.       row_3        4      5     10     11     no
  137. -----------------------------------------------------------concat-------------------------
  138. yes    row_5        2      4     18     19    yes
  139.       row_2        5      8      6      7    yes
  140.       row_6        6      6     22     23    yes
  141.      
  142. test2.groupby('smoker',group_keys=False).apply(top,n=3):
  143.       tip_pct  col_2  col_3  col_4 smoker
  144. row_1        2      7      2      3     no
  145. row_3        4      5     10     11     no
  146. row_5        2      4     18     19    yes
  147. row_2        5      8      6      7    yes
  148. row_6        6      6     22     23    yes  
  149.      
  150. 用特定于分组的值填充缺失值:       '''
  151. s=Series(np.random.rand(6))
  152. s[::2]=np.nan#步长为2
  153. '''
  154. s:
  155. 0         NaN
  156. 1    0.654905
  157. 2         NaN
  158. 3    0.475528
  159. 4         NaN
  160. 5    0.269656
  161. dtype: float64
  162. s.fillna(s.mean())
  163. Out[208]:
  164. 0    0.466696
  165. 1    0.654905
  166. 2    0.466696
  167. 3    0.475528
  168. 4    0.466696
  169. 5    0.269656
  170. dtype: float64
  171. '''
  172. s.fillna(s.mean())      


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