有一个带有463916行的CSV文件。第一列是性别列。1是男性,2是女性。第二列是年龄。它有0到85。第三列是教育水平,但我们不需要这项作业领域。
我想要这样的结果。
男性女性
以下10 0.5 0.5
S10(10(0.4 0.6
s20(20's(0.5 0.5
s30(20's(0.5 0.5
s40(20's(0.5 0.5
s50(20's(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()
问题是data[:,1]
为您提供了整列。很好,但是您的wir循环应该宁愿迭代值。
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