需求:
兩個文件,一個文件為統計報表,里面含有手機號,另一個文件為手機號段歸屬地,含有手機號碼前七位對應的地區。需要對統計報表進行處理,將手機號所在的歸屬地加入到統計報表中,使用pandas提供的join功能來實現,代碼如下:
#coding=utf-8from pandas import Series,DataFrameimport pandas as pd#reader1 = pd.read_csv('Dm_Mobile.txt',iterator=True,encoding="gb2312")#df1 = reader1.get_chunk(10)#reader2 = pd.read_csv('201604.csv',iterator=True,encoding="gb2312")#df2 = reader.get_chunk(10)#讀取兩個csv文件,生成dataframedf1 = pd.read_csv('Dm_Mobile.csv',encoding="gb2312")df2 = pd.read_csv('201604.csv',encoding="gb2312")#截取手機號前七位,作為新列添加到dataframedf2['p7s'] = Series([str(x)[:7] for x in Series(df2[u'手機號'])])df2['p7i'] = df2['p7s'].astype("int64")#在兩個dataframe的手機前七位列上創建索引index_df1 = df1.set_index('MobileNumber')index_df2 = df2.set_index(['p7i'])#以手機號前七位列為join列,對兩個dataframe進行joinresult = pd.concat([index_df1, index_df2], axis=1, join='inner')#選取需要顯示的列,重新生成resultresult = result.reindex(columns=[u'積分商城訂單號', u'手機號',u'產品編碼',u'商品名稱',u'商品價格',u'數量',u'虛擬碼',u'消費時間',u'時間',u'兌換渠道商',u'MobileArea'])#寫入到excel文件中writer = pd.ExcelWriter('pandas_simple.xlsx')result.to_excel(writer, sheet_name=u'設計院',index=False)writer.save()
以上這篇使用pandas對兩個dataframe進行join的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答