如何修复python切片和索引时的值错误?

2024-10-05 10:19:33 发布

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

有一个包含463916行的csv文件。 第一栏是性别栏。 1是男性,2是女性。 第二栏是年龄。 它有0到85。 第三栏是教育程度,但我们不需要这个领域的家庭作业

我想要这样的结果

男-女

低于10 0.5 0.5

s10(10秒)0.4 0.6

s20(20秒)0.5 0.5

s30(20英寸)0.5 0.5

s40(20英寸)0.5 0.5

s50(20英寸)0.5 0.5

60以上0.6 0.4

我找到了每个年龄组的人口,但是在获得性别比例的函数中有一个错误。我不知道我该怎么对付60多岁的人! 但是我不能用熊猫因为我还没学会。。。 我是python的初学者。请帮帮我

数据如下

array([[ 1,  0,  1],
       [ 1,  0,  1],
       [ 1,  0,  1],
       ...,
       [ 2, 85,  6],
       [ 2, 85,  7],
       [ 2, 85,  7]], dtype=int64)


import numpy as np
data = np.loadtxt("population.csv", delimiter = ",", dtype = 'int64')

under10=s10=s20=s30=s40=s50=over60=0

def sex(age, total):
    male=female=0
    while(data[:,1]<age):
        if(data[:,0]==1):
            male+=1    
        else:
            break
    female=total-male
    print(male/total,female/total)

for i in data[:,1]:
    if (i<10):
        under10 += 1
    elif (i<20):
        s10 +=1
    elif (i<30):
        s20 +=1
    elif (i<40): 
        s30 +=1
    elif (i<50):
        s40 +=1
    elif (i<60):
        s50 +=1
    else:
        over60 +=1
sex(10, under10)
sex(20, s10)
sex(30, s20)
sex(40, s30)
sex(50, s40)
sex(60, s50)
sex(?)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-53c9486669b3> in <module>
     31     else:
     32         over60 +=1
---> 33 sex(10, under10)

<ipython-input-51-53c9486669b3> in sex(age, total)
      6 def sex(age, total):
      7     male=female=0
----> 8     while(data[:,1]<age):
      9         if(data[:,0]==1):
     10             male+=1

ValueError: The truth value of an array with more than one element is         ambiguous. Use a.any() or a.all()

Tags: agedatamalefemaletotalelif英寸s10
1条回答
网友
1楼 · 发布于 2024-10-05 10:19:33

问题是data[:,1]给出了整个列。这很好,但是while循环应该迭代这些值

for row in data:
    # row is array([1, 0, 1])
    if row[1] < age:
        # row[1] is 0
        if row[0] == 1:
           # row[1] is 0
           male += 1

相关问题 更多 >

    热门问题