gpt4 book ai didi

arrays - 如何将包装为字符串的向量转换为 Pandas 数据帧中的 numpy 数组?

转载 作者:行者123 更新时间:2023-12-03 20:17:51 25 4
gpt4 key购买 nike

我有一个带有一列向量的 Pandas 数据框,我想对其执行矩阵运算。然而,经过仔细检查,这些向量都被包装成字符串,其中似乎嵌入了换行符:

enter image description here

如何将此列中的每个向量转换为 numpy 数组?我试过了

df['Word Vector'].as_matrix


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


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

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

最佳答案

希望以下内容如您所愿

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, ...

多次调用replace函数并不优雅。但是我没有找到更好的方法。无论如何,它应该可以帮助您将字符串转换为向量。

附注,由于数据以图片形式呈现,您最好检查一下您的数据分隔是按空格还是按制表符完成的。如果是制表符,将 sep=' ' 改为 sep='\t'

关于arrays - 如何将包装为字符串的向量转换为 Pandas 数据帧中的 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45704999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com