pandas常用
#python中的pandas庫主要有DataFrame和Series類(面向?qū)ο蟮牡恼Z言更愿意叫類) DataFrame也就是
#數(shù)據(jù)框(主要是借鑒R里面的data.frame),Series也就是序列 ,pandas底層是c寫的 性能很棒,有大神
#做過測試 處理億級(jí)別的數(shù)據(jù)沒問題,起性能可以跟同等配置的sas媲美
#DataFrame索引 df.loc是標(biāo)簽選取操作,df.iloc是位置切片操作
print(df[['row_names','Rape']])
df['行標(biāo)簽']
df.loc[行標(biāo)簽,列標(biāo)簽]
print(df.loc[0:2,['Rape','Murder']])
df.iloc[行位置,列位置]
df.iloc[1,1]#選取第二行,第二列的值,返回的為單個(gè)值
df.iloc[0,2],:]#選取第一行及第三行的數(shù)據(jù)
df.iloc[0:2,:]#選取第一行到第三行(不包含)的數(shù)據(jù)
df.iloc[:,1]#選取所有記錄的第一列的值,返回的為一個(gè)Series
df.iloc[1,:]#選取第一行數(shù)據(jù),返回的為一個(gè)Series
print(df.ix[1,1]) # 更廣義的切片方式是使用.ix,它自動(dòng)根據(jù)你給到的索引類型判斷是使用位置還是標(biāo)簽進(jìn)行切片
print(df.ix[0:2])
#DataFrame根據(jù)條件選取子集 類似于sas里面if、where ,R里面的subset之類的函數(shù)
df[df.Murder>13]
df[(df.Murder>10)&(df.Rape>30)]
df[df.sex==u'男']
#重命名 相當(dāng)于sas里面的rename R軟件中reshape包的中的rename
df.rename(columns={'A':'A_rename'})
df.rename(index={1:'other'})
#刪除列 相當(dāng)于sas中的drop R軟件中的test['col']<-null
df.drop(['a','b'],axis=1) or del df[['a','b']]
#排序 相當(dāng)于sas里面的sort R軟件里面的df[order(x),]
df.sort(columns='C') #行排序 y軸上
df.sort(axis=1) #各個(gè)列之間位置排序 x軸上
#數(shù)據(jù)描述 相當(dāng)于sas中proc menas R軟件里面的summary
df.describe()
#生成新的一列 跟R里面有點(diǎn)類似
df['new_columns']=df['columns']
df.insert(1,'new_columns',df['B']) #效率最高
df.join(Series(df['columns'],name='new_columns'))
#列上面的追加 相當(dāng)于sas中的append R里面cbind()
df.append(df1,ignore_index=True)
pd.concat([df,df1],ignore_index=True)
#最經(jīng)典的join 跟sas和R里面的merge類似 跟sql里面的各種join對(duì)照
merge()
#刪除重行 跟sas里面nodukey R里面的which(!duplicated(df[])類似
df.drop_duplicated()
#獲取最大值 最小值的位置 有點(diǎn)類似矩陣?yán)锩娴姆椒?br />df.idxmin(axis=0 ) df.idxmax(axis=1) 0和1有什么不同 自己摸索去
#讀取外部數(shù)據(jù)跟sas的proc import R里面的read.csv等類似
read_excel() read_csv() read_hdf5() 等
與之相反的是df.to_excel() df.to_ecv()
#缺失值處理 個(gè)人覺得pandas中缺失值處理比sas和R方便多了
df.fillna(9999) #用9999填充
#鏈接數(shù)據(jù)庫 不多說 pandas里面主要用 MySQLdb
import MySQLdb
conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="mysql",use_unicode=True,charset="utf8")
read_sql() #很經(jīng)典
#寫數(shù)據(jù)進(jìn)數(shù)據(jù)庫
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函數(shù)類似
pd.pivot_table()
pd.crosstab()
#聚合函數(shù)經(jīng)常跟group by一起組合用
df.groupby('sex').agg({'height':['mean','sum'],'weight':['count','min']})
#數(shù)據(jù)查詢過濾
test.query("0.2
將STK_ID中的值過濾出來
stk_list = ['600809','600141','600329']中的全部記錄過濾出來,命令是:rpt[rpt['STK_ID'].isin(stk_list)].
將dataframe中,某列進(jìn)行清洗的命令
刪除換行符:misc['product_desc'] = misc['product_desc'].str.replace('\n', '')
刪除字符串前后空格:df["Make"] = df["Make"].map(str.strip)
如果用模糊匹配的話,命令是:
rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')]
對(duì)dataframe中元素,進(jìn)行類型轉(zhuǎn)換
df['2nd'] = df['2nd'].str.replace(',','').astype(int) df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
#時(shí)間變換 主要依賴于datemie 和time兩個(gè)包
http://www.2cto.com/kf/201401/276088.html
#其他的一些技巧
df2[df2['A'].map(lambda x:x.startswith('61'))] #篩選出以61開頭的數(shù)據(jù)
df2["Author"].str.replace("<.+>", "").head() #replace("<.+>", "")表示將字符串中以”<”開頭;以”>”結(jié)束的任意子串替換為空字符串
commits = df2["Name"].head(15)
print commits.unique(), len(commits.unique()) #獲的NAME的不同個(gè)數(shù),類似于sql里面count(distinct name)
#pandas中最核心 最經(jīng)典的函數(shù)apply map applymap
#這三個(gè)函數(shù)是pandas里面數(shù)據(jù)變換的核心 避免了for循環(huán),跟R里面的apply函數(shù)類似
#主要用法不清楚可以問我
pd.concat([df1,df2],axis=1) 橫向合并 ,沒有axis=1 則縱向合并
轉(zhuǎn)載于:https://www.cnblogs.com/onemorepoint/p/8135881.html
總結(jié)
- 上一篇: 八.利用springAMQP实现异步消息
- 下一篇: redis基础之订阅发布、主从复制和事务