3

でより多くの行を作るための一つの列から分割データだから私の入力は次のとおりです。Pythonのデータ操作:同じデータフレーム

Col1   Col2  Col3 Col4 
0 123 abc,def,ghi Country1 XXX 
1 456  pqr,stu Country2 XX 
2 789   xyz Country2 YY 

私は私の出力をしたいなど:

ほとんどだろう何
Col1  Col2 Col3 Col4 
0 abc  123 Country1 XXX 
1 def  123 Country1 XXX 
2 ghi  123 Country1 XXX 
3 pqr  456 Country2  XX 
4 stu  456 Country2  XX 
5 xyz  789 Country2  YY 

これを行うpythonic方法pls?ありがとうVM!

あなたが元 DataFramejoinため Seriesを作成するための stackstr.splitを使用することができます

答えて

3

extractallを使用して
print (df.Col2 
     .str 
     .split(',',expand=True) 
     .stack() 
     .reset_index(drop=True, level=1) 
     .rename('Col2')) 

0 abc 
0 def 
0 ghi 
1 pqr 
1 stu 
2 xyz 
Name: Col2, dtype: object 


print (df.drop('Col2', axis=1) 
      .join 
      (
      df.Col2 
      .str 
      .split(',',expand=True) 
      .stack() 
      .reset_index(drop=True, level=1) 
      .rename('Col2')   
      )) 

    Col1  Col3 Col4 Col2 
0 123 Country1 XXX abc 
0 123 Country1 XXX def 
0 123 Country1 XXX ghi 
1 456 Country2 XX pqr 
1 456 Country2 XX stu 
2 789 Country2 YY xyz 
+0

AHA - '拡大= true'を分割で+スタック!本当にありがとう! – spiff

3

join

d1 = df.Col2.str.extractall('([^,]+)') \ 
     .rename(columns={0: 'Col2'}) \ 
     .reset_index(1, drop=True) 

df.drop('Col2', 1).join(d1).reindex_axis(df.columns, 1) 

enter image description here

+0

ああ興味深い - 「extractall」について知りませんでした..ありがとう – spiff

関連する問題