numpy python IndexError:布尔索引与沿着维度0的索引数组不匹配;维度为32,但相应的布尔维度为112

zhte4eai  于 2023-08-05  发布在  Python
关注(0)|答案(1)|浏览(132)

我是Matploblib和Numpy的新手,在尝试提取数据时遇到过问题。以下代码将导致IndexError:布尔索引与沿着维度0的索引数组不匹配;维度是32,但对应的布尔维度是112。请指教!!
使用的数据集:https://data.gov.sg/dataset/monthly-motor-vehicle-population-by-type-of-fuel-used

import numpy as np
import matplotlib.pyplot as plt
title = "motor-vehicle-population-statistics-by-type-of-fuel-used."
titlelen = len(title)
print("{:*^{titlelen}}".format(title, titlelen=titlelen+6))
print()
data = np.genfromtxt("data/motor-vehicle-population-statistics-by-type-of-fuel-used.csv",
                      dtype=("datetime64[Y]","U100","U110",int),
                      delimiter=",",
                      names=True)

years = np.unique(data["month"])
category = np.unique(data['category'])
type = np.unique(data['type'])

cars = data[data["category"]=="Cars"]["number"]
carspetrol = cars[data["type"]=="Petrol"]["number"]
# print(cars)
print(carspetrol)

字符串

lokaqttq

lokaqttq1#

你在这里有一些问题。
第一个不使用python关键字作为变量

type = np.unique(data['type'])

字符串
到这个

types = np.unique(data['type'])


你的错误是你试图比较一个有112个值的布尔数组(data)和一个32个元素的数组(cars)。所以你的代码应该像这样改变

cars = data[data["category"]=="Cars"]
carspetrol = cars[cars["type"]=="Petrol"]["number"]


此外,使用像Pandas这样的分析库来做基本分析比numpy更好。

相关问题