2016-12-02 86 views
2

我的一個數據幀的小樣本是在該格式分裂文本&使用熊貓

**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 

現在我想分裂產物塔在python相應追加。我知道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的。你可以請指導我如何繼續獲得上述輸出?提前致謝。

回答

3

可以使用str.strip用於去除,str.splitstack創建Seriesjoin原始DataFrame

reset_indexindex避免重複和重新排序列名由reindex_axis

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