gpt4 book ai didi

python-3.x - 在 numpy 中获取索引

转载 作者:行者123 更新时间:2023-12-01 02:30:43 25 4
gpt4 key购买 nike

有人能找出下面代码有什么问题吗?

import numpy as np
data = np.recfromcsv("data.txt", delimiter=" ", names=['name', 'types', 'value'])
indices = np.where((data.name == 'david') * data.types.startswith('height'))
mean_value = np.mean(data.value[indices])

我想计算 david 的体重和高度的平均值并标记如下:

david>> mean(weight_2005 and weight_2012), mean (height_2005 and height_2012)
mark>> mean(weight_2005 and weight_2012), mean (height_2005 and height_2012)

来自文本(data.txt)文件:

david weight_2005 50
david weight_2012 60
david height_2005 150
david height_2012 160
mark weight_2005 90
mark weight_2012 85
mark height_2005 160
mark height_2012 170

我正在使用 python 3.2 和 numpy 1.8

以上代码提供的类型错误如下:

TypeError: startswith first arg must be bytes or a tuple of bytes, not numpy.str_

最佳答案

对于 Python3.2 和 numpy 1.7,这条线有效

indices = np.where((data.name == b'david') * data.types.startswith(b'height'))

data显示为:

rec.array([(b'david', b'weight_2005', 50),...], 
dtype=[('name', 'S5'), ('types', 'S11'), ('value', '<i4')])

type(data.name[0])<class 'bytes'> .

b'height'也适用于 Python2.7。


另一种选择是将所有数据转换为 unicode(Python 3 字符串)

dtype=[('name','U5'), ('types', 'U11'), ('value', '<i4')]
dataU=data.astype(dtype=dtype)
indices = np.where((dataU.name == 'david') * dataU.types.startswith('height'))

data = np.recfromtxt('data.txt', delimiter=" ", 
names=['name', 'types', 'value'], dtype=dtype)

看起来像recfromcsv不需要 dtype ,但是 recfromtxt

关于python-3.x - 在 numpy 中获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19944408/

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