天天看点

python中pandas库学习笔记

原址 http://blog.sina.com.cn/s/blog_7d8326290102vzpx.html

#python中的pandas库主要有DataFrame和Series类(面向对象的的语言更愿意叫类) DataFrame也就是 #数据框(主要是借鉴R里面的data.frame),Series也就是序列 ,pandas底层是c写的 性能很棒,有大神 #做过测试  处理亿级别的数据没问题,起性能可以跟同等配置的sas媲美 #DataFrame索引  df.loc是标签选取操作,df.iloc是位置切片操作 print(df[['row_names','Rape']]) df['行标签'] df.loc[行标签,列标签] print(df.loc[0:2,['Rape','Murder']]) df.iloc[行位置,列位置] df.iloc[1,1]#选取第二行,第二列的值,返回的为单个值 df.iloc[0,2],:]#选取第一行及第三行的数据 df.iloc[0:2,:]#选取第一行到第三行(不包含)的数据 df.iloc[:,1]#选取所有记录的第一列的值,返回的为一个Series df.iloc[1,:]#选取第一行数据,返回的为一个Series print(df.ix[1,1])  # 更广义的切片方式是使用.ix,它自动根据你给到的索引类型判断是使用位置还是标签进行切片 print(df.ix[0:2])

#DataFrame根据条件选取子集  类似于sas里面if、where ,R里面的subset之类的函数 df[df.Murder>13] df[(df.Murder>10)&(df.Rape>30)] df[df.sex==u'男'] #重命名  相当于sas里面的rename   R软件中reshape包的中的rename df.rename(columns={'A':'A_rename'})   df.rename(index={1:'other'})

#删除列  相当于sas中的drop  R软件中的test['col']<-null df.drop(['a','b'],axis=1)  or  del  df[['a','b']]

#排序  相当于sas里面的sort   R软件里面的df[order(x),] df.sort(columns='C')   #行排序  y轴上 df.sort(axis=1)  #各个列之间位置排序  x轴上

#数据描述  相当于sas中proc menas  R软件里面的summary df.describe()

#生成新的一列  跟R里面有点类似 df['new_columns']=df['columns'] df.insert(1,'new_columns',df['B'])  #效率最高 df.join(Series(df['columns'],name='new_columns'))

#列上面的追加  相当于sas中的append   R里面cbind() df.append(df1,ignore_index=True) pd.concat([df,df1],ignore_index=True)

#最经典的join   跟sas和R里面的merge类似   跟sql里面的各种join对照 merge()

#删除重行  跟sas里面nodukey   R里面的which(!duplicated(df[])类似 df.drop_duplicated()

#获取最大值  最小值的位置   有点类似矩阵里面的方法 df.idxmin(axis=0 ) df.idxmax(axis=1)  0和1有什么不同  自己摸索去

#读取外部数据跟sas的proc  import  R里面的read.csv等类似 read_excel()  read_csv()  read_hdf5() 等

与之相反的是df.to_excel()   df.to_ecv()

#缺失值处理  个人觉得pandas中缺失值处理比sas和R方便多了 df.fillna(9999)  #用9999填充  

#链接数据库 不多说    pandas里面主要用 MySQLdb import MySQLdb conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="mysql",use_unicode=True,charset="utf8") read_sql() #很经典 #写数据进数据库 df.to_sql('hbase_visit',con, flavor="mysql", if_exists='replace', index=False)

#groupby  跟sas里面的中的by    R软件中dplyr包中的group_by  sql里面的group by功能是一样的 这里不多说

#求哑变量   dumiper=pd.get_dummies(df['key']) df['key'].join(dumpier)

#透视表  和交叉表   跟sas里面的proc  freq步类似  R里面的aggrate和cast函数类似 pd.pivot_table() pd.crosstab()

#聚合函数经常跟group by一起组合用 df.groupby('sex').agg({'height':['mean','sum'],'weight':['count','min']})  

#数据查询过滤

test.query("0.2      
将STK_ID中的值过滤出来      
stk_list = ['600809','600141','600329']中的全部记录过滤出来,命令是:                rpt[rpt['STK_ID'].isin(stk_list)].      
将dataframe中,某列进行清洗的命令      
对dataframe中元素,进行类型转换

           
df['2nd'] = df['2nd'].str.replace(',','').astype(int) df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
           

#时间变换  主要依赖于datemie  和time两个包 http://www.2cto.com/kf/201401/276088.html

#其他的一些技巧 df2[df2['A'].map(lambda x:x.startswith('61'))]  #筛选出以61开头的数据 df2["Author"].str.replace("<.+>", "").head()  #replace("<.+>", "")表示将字符串中以”<”开头;以”>”结束的任意子串替换为空字符串

commits = df2["Name"].head(15) print commits.unique(), len(commits.unique())   #获的NAME的不同个数,类似于sql里面count(distinct name)

#pandas中最核心 最经典的函数apply  map   applymap

#这三个函数是pandas里面数据变换的核心  避免了for循环,跟R里面的apply函数类似 #主要用法不清楚可以问我

继续阅读