2016-12-02 3 views
2

一つの小さなサンプルでは、​​今私は、製品の列を分割したいという形式で分割テキスト&パンダを使用してpythonでそれに応じて追加

**shop** **product** **location** **time** **count_products** 
store1  ,A,B,C  X   8.30 pm  3 
store1  ,G,F   Y   8.41 pm  2 
store1  ,C,D,T,R  Z   9.02 pm  4 

です。私はstr.splitが特別な文字を分割できることを知っています&私は列を分割することができます。私は次の形式を持つ必要があります生成したい出力、

**shop** **product** **location** **time** **count_products** 
store1  A    X   8.30 pm   3 
store1  B    X   8.30 pm   3 
store1  C    X   8.30 pm   3    
store1  G    Y   8.41 pm   2 
store1  F    Y   8.41 pm   2 
store1  C    Z   9.02 pm   4 
store1  D    Z   9.02 pm   4 
store1  T    Z   9.02 pm   4 
store1  R    Z   9.02 pm   4 

私はパンダに& numpyのを使用しています。上記の出力を得るためにどのように進めることができますか教えてください。前もって感謝します。元DataFramejoinためSeriesを作成するためのstack,str.splitを取り除くため

答えて

3

あなたはstr.stripを使用することができます。 reindex_axisによって

indexで回避の重複の

最終reset_indexと並べ替え列名:

print (
df.pop('**product**') 
.str 
.strip(',') 
.str 
.split(',',expand=True) 
.stack() 
.reset_index(drop=True, level=1) 
.rename('**product**')   
) 
0 A 
0 B 
0 C 
1 G 
1 F 
2 C 
2 D 
2 T 
2 R 
Name: **product**, dtype: object 
cols = df.columns 

print (df.join 
      (
      df.pop('**product**') 
      .str 
      .strip(',') 
      .str 
      .split(',',expand=True) 
      .stack() 
      .reset_index(drop=True, level=1) 
      .rename('**product**')   
      ).reset_index(drop=True) 
       .reindex_axis(cols,axis=1)) 

    **shop** **product** **location** **time** **count_products** 
0 store1   A   X 8.30 pm     3 
1 store1   B   X 8.30 pm     3 
2 store1   C   X 8.30 pm     3 
3 store1   G   Y 8.41 pm     2 
4 store1   F   Y 8.41 pm     2 
5 store1   C   Z 9.02 pm     4 
6 store1   D   Z 9.02 pm     4 
7 store1   T   Z 9.02 pm     4 
8 store1   R   Z 9.02 pm     4 
+0

すごい..優れた –

+0

私は –

+0

アップ投票していますありがとうございました、しかし、あなたはまた、空にする]をクリックすることができます緑の場合は「1」にチェックを入れてください。 – jezrael

関連する問題