如何将包装为字符串的矢量转换为熊猫数据框中的numpy数组?

问题描述:

我有一列熊猫数据帧,我想对其执行矩阵运算。然而,经仔细检查向量都包裹与新行字符的字符串看似嵌入其中:如何将包装为字符串的矢量转换为熊猫数据框中的numpy数组?

enter image description here

如何转换在此列中的每个载体导入numpy的阵列?我试过

df['Word Vector'].as_matrix 

np.array(df['Word Vector']) 

以及

df['Word Vector'] = df['Word Vector'].astype(np.array) 

但没有产生预期的结果。任何指针将不胜感激!

+0

利用我们可以尝试的数据示例。 – MedAli

+0

@MedAli最好的办法是什么?我不确定这个过程是否生成了这种格式,我怎样才能将数据框的样本上传到stackoverflow? – Matt

希望下面的作品你所期望的

import pandas as pd 
import numpy as np 

x = str(np.arange(1,100)) 
df = pd.DataFrame([x,x,x,x]) 
df.columns = ['words'] 
print 'sample' 
print df.head() 
result = df['words'].apply(lambda x: 
          np.fromstring(
           x.replace('\n','') 
           .replace('[','') 
           .replace(']','') 
           .replace(' ',' '), sep=' ')) 
print 'result' 
print result 

输出如下

sample 
               words 
0 [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 
1 [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 
2 [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 
3 [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ... 
result 
0 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, ... 
1 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, ... 
2 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, ... 
3 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, ... 

这是不优雅调用替换功能这么多次。但是我没有找到更好的方法。无论如何,它应该可以帮助你将字符串转换为矢量。

一个方面的说明,因为数据显示在图片中,您最好检查您的数据分隔是通过空间还是制表符来完成。如果是选项卡,请将sep =''更改为sep ='\ t'