将熊猫系列转换为numpy数组[重复]

问题描述 投票:26回答:3

我是熊猫和蟒蛇的新手。我的输入数据就像

category   text
1   hello iam fine. how are you
1   iam good. how are you doing.

inputData= pd.read_csv(Input', sep='\t', names=['category','text'])
X = inputData["text"]
Y = inputData["category"]

这里Y是熊猫系列对象,我想将其转换为numpy数组。所以我尝试了.as_matrix

YArray= Y.as_matrix(columns=None)
print YArray

但是我得到的输出为[1,1](这是错误的,因为我只有一列类别和两行)。我希望结果为2x1矩阵。

python-2.7 pandas numpy
3个回答
10
投票

尝试一下:在系列对象上应用.as_matrix之后

Y.reshape((2,1))

因为.as_matrix()仅返回一个numpy数组,而不返回numpy-matrix。Link here


43
投票

要获取numpy数组,您需要

Y.values

7
投票

如果df是您的数据框,则该数据框的一列是一个序列,并将其转换为数组,

df = pd.DataFrame()
x = df.values
print(x.type)

以下印刷品,

<class 'numpy.ndarray'>

成功将其转换为数组。

© www.soinside.com 2019 - 2024. All rights reserved.