Mat*_*att 5 arrays string numpy type-conversion pandas
我有一个带有一列向量的 Pandas 数据框,我想对其执行矩阵运算。然而,经过仔细检查,这些向量都被包装成字符串,其中似乎嵌入了换行符:
如何将此列中的每个向量转换为 numpy 数组?我试过了
df['Word Vector'].as_matrix
Run Code Online (Sandbox Code Playgroud)
和
np.array(df['Word Vector'])
Run Code Online (Sandbox Code Playgroud)
也
df['Word Vector'] = df['Word Vector'].astype(np.array)
Run Code Online (Sandbox Code Playgroud)
但没有产生预期的结果。任何指针将不胜感激!
希望以下内容如您所愿
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
Run Code Online (Sandbox Code Playgroud)
输出如下
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, ...
Run Code Online (Sandbox Code Playgroud)
多次调用replace函数并不优雅。但是我没有找到更好的方法。无论如何,它应该可以帮助您将字符串转换为向量。
附注,由于数据以图片形式呈现,您最好检查一下您的数据分隔是按空格还是按制表符完成的。如果是制表符,将 sep=' ' 改为 sep='\t'
| 归档时间: |
|
| 查看次数: |
6046 次 |
| 最近记录: |