读取数据文件(鲍鱼)并转换为numpy数组

2024-03-29 11:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试加载UCI鲍鱼数据文件时,如下所示:

dattyp = [('sex',object),('length',float),('diameter',float),('height',float),('whole weight',float),('shucked weight',float),('viscera weight',float),('shell weight',float),('rings',int)]

abalone_data = np.loadtxt('C:/path/abalone.dat',dtype = dattyp, delimiter = ',')

print(abalone_data.shape)
print(abalone_data[0])
>>(4177,)
  ('M',  0.455,  0.365,  0.095,  0.514,  0.2245,  0.101,  0.15, 15)

Abalone_data是具有1列而不是9列的数组。稍后,当我想添加其他数据作为额外的列时,这会给我带来问题。有没有办法把这些数据转换成(4177, 9)矩阵,在那里我可以做通常的列添加等?
谢谢!你知道吗


Tags: 数据dataobject数据文件floatlengthprintheight
2条回答

您可以使用熊猫:

import pandas as pd

abalone_data = pd.read_csv('C:/path/abalone.dat', header=None).values
abalone_data.shape

输出:

(4177, 9)

您可以将unpack参数添加到numpy.loadtxt()。然后可以numpy.transpose()新创建的numpy数组以获得所需的数组形状。你知道吗

import numpy as np

dattyp = [('sex',object),('length',float),('diameter',float),('height',float),('whole weight',float),('shucked weight',float),('viscera weight',float),('shell weight',float),('rings',int)]

abalone_data = np.loadtxt('C:/path/abalone.dat',dtype = dattyp, delimiter = ',', unpack=True)
abalone_data = np.array((abalone_data)).transpose()

print(abalone_data.shape)

输出:

(4177, 9)

来自文档:

unpack : bool, optional

If True, the returned array is transposed, so that arguments may be unpacked using x, y, z = loadtxt(...). When used with a structured data-type, arrays are returned for each field. Default is False.

相关问题 更多 >