nam访问列数据时出错

2024-04-25 23:01:18 发布

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

我无法通过列名从结构化numpy数组获取数据。最后是我的相关代码。我认为这是简单和短到足以张贴在整个(这是一个sscce准确)。你知道吗

如果test.out文件不存在,只需简单地将数据生成。我总是从文件中加载数据,只是为了测试。我认为这在这里并不重要。然后,如果文件中的数据是同质的,我强制使用结构化数组。我想通过data['f3']这样的列名访问数据,但我得到的是一种奇怪的形状。我得到一个单元素列表。例如:

shape: (10, 1), data['f3']:
[[ 0.50308252]
 [ 0.16259077]
 [ 0.5448315 ]
 [ 0.77284975]
 [ 0.01443514]
 [ 0.40232731]
 [ 0.6703865 ]
 [ 0.3918904 ]
 [ 0.07649033]
 [ 0.70849585]]

所需输出为:

shape: (10, 1), data['f3']:
[ 0.50308252  0.16259077  0.5448315   0.77284975  0.01443514  0.40232731
  0.6703865   0.3918904   0.07649033  0.70849585]

有趣的是,所有报告的形状都是相同的(对于data.shape)。你知道吗

我执行dtype的方式不对吗?我很肯定这是可以做到的,因为this answer显示了相同的语义和期望的结果。我用reshape找到了一个解决方法,但如果有必要的话,它看起来很奇怪。这也适用于列列表。您可以在我的代码中设置col_name = ['f1', 'f3']。有没有办法用一个简单的data[col_name]来完成?你知道吗

代码:

import numpy
import os

def get_data():
  if not os.path.exists('test.out'):
    new_data = numpy.random.rand(10,10)
    numpy.savetxt('test.out', new_data, delimiter=',')
  data = numpy.genfromtxt('test.out',delimiter=",", dtype=None)
  return data


def get_column(spreadsheet, column):
  data = spreadsheet[column]
  return data.reshape(data.shape[0])

data = get_data()
#if data is homogenous, then forcibly transform into structured array
if data.dtype.names is None:
  new_dtype = list(map(lambda z:('f%d'%(z),data.dtype),range(0,data.shape[1])))
  #print('old dtype: {}, new dtype: {}'.format(data.dtype, new_dtype))
  data.dtype = new_dtype

col_name = 'f3'
print(data.dtype)
print("shape: {}, data:\n{}".format(data.shape, data))
print("shape: {}, data['{}']:\n{}".format(data[col_name].shape, col_name, data[col_name]))
print("shape: {}, data['{}']:\n{}".format(data[col_name].shape, col_name, get_column(data, col_name)))

Tags: 数据nametestnumpyformatnewdataget
1条回答
网友
1楼 · 发布于 2024-04-25 23:01:18

当指定新的数据类型以使data成为结构化数组时,形状将从(10,10)更改为(10,1)。也就是说,它仍然是一个二维数组,第二个维度的长度为1。如果结构化数组是由genfromtxt创建的,那么形状将是(10,)(即,它将是一维数组)。在指定数据类型后,还可以通过指定新形状来完成相同的操作:

  data.shape = data.shape[0]

或将data.dtype = new_dtype替换为

  data = data.view(new_dtype).reshape(-1)

然后结构化阵列具有形状(10,),并且data['f3']也具有形状(10,)。你知道吗

请注意,从结构化数组获取字段,例如data,是一个与data形状相同的数组。也就是说,data['f3']总是具有与data相同的形状。它是结构化数组的“f3”字段的数组。我们通常认为字段是“列”(特别是当结构化数组是1-d时),但实际上它们只是结构中字段的名称。你知道吗

相关问题 更多 >