在大熊猫数据帧转换列到多列

在大熊猫数据帧转换列到多列

问题描述:

我有其中有一列中的下列值的列的熊猫数据帧:在大熊猫数据帧转换列到多列

Identifier 
[1;12;7;3;0] 
[4;5;2;6;0] 

我想在方括号中的数值转换在此列5个新栏目。实质上,我想将这些值分成5个新列,同时保持新列的索引与原始列相同。

Identifier,a,b,c,d,e 
[1;12;7;3;0],1,12,7,3,0 
[4;5;2;6;0],4,5,2,6,0 

pattern = re.compile(r'(\d+)') 
for g in raw_data["Identifier"]: 
    new_id = raw_data.Identifier.str.findall(pattern) # this converts the Identifier into a list of the 5 values 
raw_data.append({'a':new_id[0],'b':new_id[1],'c':new_id[2],'d':new_id[3],'d':new_id[4]}, ignore_index=True) 

上面的代码将从“标识符”列中提取的值添加到DataFrame的末尾而不是相应的行。我如何将提取的值添加到与原始列('标识符')相同的行/索引?

其中一种方法是使用str方法获取数字,从中创建一个新的数据框,然后加入(或连接)结果。例如,

id_data = df.Identifier.str.strip("[]").str.split(";").tolist() 
df_id = pd.DataFrame(id_data, columns=list("abcde"), index=df.index, dtype=int) 
df2 = df.join(df_id) 

产生类似

 Identifier a b c d e 
10 [1;12;7;3;0] 1 12 7 3 0 
20 [4;5;2;6;0] 4 5 2 6 0 
+0

这是完美的。谢谢! – kkhatri99 2014-09-21 02:03:17