Python dataframe列拆分多行与统计
生活随笔
收集整理的這篇文章主要介紹了
Python dataframe列拆分多行与统计
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
7.2.4 列拆分多行與統(tǒng)計
需求:對原因字段里按照分隔符拆分并匯總統(tǒng)計分析
解決方法:通過Python的DataFrame、Mysql結合row_number進行統(tǒng)計完成該需求。
# coding=utf8 import pandas as pd#返回<br/>的個數(shù) def fuc_brCnt(col):return col['REJECT'].count('<br/>',0,600)def tidy_split(df, column, sep='|', keep=False):indexes = list()new_values = list()df = df.dropna(subset=[column])for i, presplit in enumerate(df[column].astype(str)):values = presplit.split(sep)if keep and len(values) > 1:indexes.append(i)new_values.append(presplit)for value in values:indexes.append(i)new_values.append(value)new_df = df.iloc[indexes, :].copy()new_df[column] = new_valuesreturn new_df#返回冒號的個數(shù) def fuc_ColonCnt(col):return col['REJECT'].count(':',0,600)def couple_single(df,df_isApply,type):newtab1_isApply = df[df_isApply]newtab1_isApply.to_csv(r'D:\newtab1_is'+type+'.csv')newtab1_isApply_1 = tidy_split(newtab1_isApply.iloc[:, :], 'REJECT', sep='`')newtab1_isApply_1.to_csv(r'D:\newtab1_is'+type+'_1.csv')newtab1_isApply_2 = tidy_split(newtab1_isApply_1.iloc[:, :], 'REJECT', sep='-')newtab1_isApply_2.reset_index(level=0, inplace=True)newtab1_isApply_2.rename(columns={'index': 'IDX_OLD'}, inplace=True)newtab1_isApply_2.to_csv(r'D:\newtab1_is'+type+'_2.csv')newtab1_isApply_2_1 = newtab1_isApply_2.iloc[::2, :].reset_index(drop=True) ##模2為0的行newtab1_isApply_2_2 = newtab1_isApply_2.iloc[1::2, :].reset_index(drop=True) ##模2為1的行newtab1_isApply_2_1.rename(columns={'REJECT': 'SECOND'}, inplace=True)newtab1_isApply_2_1.to_csv(r'D:\newtab1_is'+type+'_2_1.csv')newtab1_isApply_3 = tidy_split(newtab1_isApply_2_2.iloc[:, :], 'REJECT', sep='|')df_concat_apply = pd.concat([newtab1_isApply_2_1, newtab1_isApply_3['REJECT']], axis=1, sort=True)if type=='Apply':df_concat_apply['TYPE']=0else:df_concat_apply['TYPE'] =1df_concat_apply.rename(columns={'REJECT': 'THIRD', 'TYPE': 'FIRST'}, inplace=True)df_concat_apply['SECOND'] = df_concat_apply["SECOND"].map(lambda s: s.replace("注冊人:", '').replace("推薦人:", '')if ":" in s else s)df_concat_apply.to_csv(r'D:\df_concat_'+type+'.csv')def rejetct_split():filename = r'./input/REJACT_DETAIL_reBuild.csv'df = pd.read_csv(filename, header=0, sep="\t", names=["ID", "APPLY", "GROUP", "REJECT"])pd.set_option('display.max_rows', 999)pd.set_option('display.max_columns', 99)pd.set_option('display.width', 1000)df_ori = df.copy()### Step 1 數(shù)據(jù)清洗df_ori['REJECT']=df_ori["REJECT"].map(lambda s: s.strip("<br/>").replace(": ",':').replace("][","|").replace("]","").replace("[","").replace("<br/> ","`"))df_ori.to_csv(r'd:\df_ori.csv')### Step 2 df_ori['COLON']=df_ori.apply(fuc_ColonCnt, axis=1)df_c=df_ori[df_ori.COLON>0].reset_index(drop=True)newtab1 = tidy_split(df_c.iloc[:, :], 'REJECT',sep='#')newtab1.to_csv(r'D:\newtab1.csv')## 分割出來的空字符串過濾掉newtab1_noEmp = (newtab1["REJECT"].apply(lambda x: x!=""))newtab1=newtab1[newtab1_noEmp]newtab1['REJECT'] = newtab1["REJECT"].map(lambda s: s.strip("`").strip("|").strip(" ") ) ## 這里空格處理newtab1.to_csv(r'D:\newtab1_1.csv')### Step 3 分兩個dataframe單獨處理#newtab1_isApply = (newtab1["REJECT"].apply(lambda x: x.find("注冊人:")>=0))#couple_single(newtab1,newtab1_isApply,'Apply')newtab1_isSpouse = (newtab1["REJECT"].apply(lambda x: x.find("推薦人:") >= 0))couple_single(newtab1, newtab1_isSpouse, 'Spouse')if __name__ == '__main__':rejetct_split()示例數(shù)據(jù)
| ID | SEQ | TYPE | REASON |
| 123456 | 10052500000000029871 | sq | ?注冊人:? 硬性條件-[非本地] [申請次數(shù)]<br/> |
| 923456 | 10052500000000029882 | gq | ?推薦人:? 其他原因 |
處理結果
| AUTO_ID | IDX_OLD | ID | SEQ | TYPE | SECOND | COLON | THIRD | FIRST |
| 1 | 0 | 123456 | 10052500000000029871 | sq | 硬性條件 | 1 | 非本地 | 注冊人 |
| 2 | 0 | 123456 | 10052500000000029871 | sq | 硬性條件 | 1 | 申請次數(shù) | 注冊人 |
| 3 | 1 | 923456 | 10052500000000029882 | gq | 硬性條件 | 1 | 其它原因 | 推薦人 |
入庫reason_V2表后結合mysql統(tǒng)計分析
SELECT CNT TYPE,COUNT(1) CNT,COUNT(DISTINCT A.ID) DISTINCT_PFROM(SELECT A.SEQ,A.ID,ROW_NUMBER()OVER(PARTITION BY SEQ ORDER BY auto_ID) CNTFROM reason_V2 A )AGROUP BY CNTORDER BY CNT統(tǒng)計結果
| TYPE | CNT | DISTINCT_P |
| 10 | 376 | 287 |
| 9 | 263 | 217 |
| 7 | 173 | 126 |
總結
以上是生活随笔為你收集整理的Python dataframe列拆分多行与统计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电动三轮车哪个牌子好 推荐几款性价比高的
- 下一篇: 电动车上牌待终审是什么意思?