需要根据列值对numpy数组进行排序,但值以String格式存在

问题描述 投票:-1回答:1

我是python中的新手,需要从包含恐怖主义数据的csv文件中提取信息。

我需要提取印度排名前5位的城市,伤亡人数最多,伤亡人数=杀人(以CSV给出)+受伤(以CSV给出)。 CSV列中还提供了城市列。

输出格式应如下所示,因果关系的降序排列

city_1 casualty_1 city_2 casualty_2 city_3 casualty_3 city_4 casualty_4 city_5 casualty_5

链接到CSV- https://ninjasdatascienceprod.s3.amazonaws.com/3571/terrorismData.csv?AWSAccessKeyId=AKIAIGEP3IQJKTNSRVMQ&Expires=1554719430&Signature=7uYCQ6pAb1xxPJhI%2FAfYeedUcdA%3D&response-content-disposition=attachment%3B%20filename%3DterrorismData.csv

import numpy as np
import csv
file_obj=open("terrorismData.csv",encoding="utf8")
file_data=csv.DictReader(file_obj,skipinitialspace=True)
country=[]
killed=[]
wounded=[]
city=[]
final=[]

#Making lists
for row in file_data:
    if row['Country']=='India':
        country.append(row['Country'])
        killed.append(row['Killed'])
        wounded.append(row['Wounded'])
        city.append(row['City'])
        final.append([row['City'],row['Killed'],row['Wounded']])


#Making numpy arrays out of lists
np_month=np.array(country)
np_killed=np.array(killed)
np_wounded=np.array(wounded)
np_city=np.array(city)
np_final=np.array(final)


#Fixing blank values in final arr
for i in range(len(np_final)):
    for j in range(len(np_final[0])):
        if np_final[i][j]=='':
            np_final[i][j]='0.0'


#Counting casualities(killed+wounded) and storing in 1st column of final array
for i in range(len(np_final)):
    np_final[i,1]=float(np_final[i,1])+float(np_final[i,2])

#Descending sort on casualities column
np_final=np_final[np_final[:,1].argsort()[::-1]]

我希望np_final能够对列的重要性进行排序,但它并没有发生,因为类型(偶然性)将以'String'形式出现

任何帮助表示赞赏。

python-3.x numpy numpy-ndarray
1个回答
0
投票

我会为你提供使用Pandas。你操作日期会更容易。读取DataFrame的所有内容。它应该将数字读入数字格式。

如果你必须在读取数据时使用np,你可以简单地将你的值转换为浮点数或整数,如果没有其他错误,一切都应该有效。像这样的东西:

for row in file_data:
if row['Country']=='India':
    country.append(row['Country'])
    killed.append(int(row['Killed']))
    wounded.append(int(row['Wounded']))
    city.append(row['City'])
    final.append([row['City'],row['Killed'],row['Wounded']])
© www.soinside.com 2019 - 2024. All rights reserved.