提取人口最接近的5个国家

2024-04-28 20:47:59 发布

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

我有一个不同国家2013年人口类型序列的对象,其中国家是指数

输入示例:

Country Name     Population in 2013
Aruba            103159.0
Afghanistan      32269589.0
Angola           26015780.0
...              ...

现在我想随机挑选一个国家及其人口。我是这样做的

countr = set(country.name for country in pycountry.countries)
listofcountr=list(countr)
randcountry=random.choice(listofcountr)

现在我想找到5个国家,它们的人口和我随机找到的这个国家的人口最接近。在绝对值的意义上最接近。我怎样才能做到这一点


Tags: 对象namein示例类型序列国家指数
3条回答

由于数据量不大,您可以尝试添加减去随机国家(列表中的每个国家)的变量,并将这些差异添加到列表中,对该列表进行排序,然后在该列表上打印前5个元素,或者创建该列表前5个记录的副本

使用pandas的另一种方法可以是以下方法(请注意,这些值是伪值)——

df = pd.DataFrame({'pop':[10,20,30,15,34,23,10,12], 'country':['a','b','c','d','e','f','g','h']})
df = df.set_index('country')
df
         pop
country
a         10
b         20
c         30
d         15
e         34
f         23
g         10
h         12

现在,如果您想找到值为pop的5个最接近的国家,例如,country b,您可以尝试以下方法-

df['diff'] = (df['pop'] - df.loc['b', 'pop']).abs()
df[df.index != 'b'].sort_values(['diff']).head(5).index.tolist()
['f', 'd', 'h', 'a', 'c', 'g']

您可以计算所有国家与所选国家的绝对差异,将其保存到列表中,然后对列表进行排序。以下是一个非Numpy版本:

randcountry = random.choice(listofcountr)
pop_distance = [abs(randcountry-i) for i in listofcountr]
sorted_list = sorted(pop_distance)
five_closest = sorted_list[1:6] #excluding the first country, which is the chosen country

使用Numpy,您可以并行化(加速)操作,如下所示:

import numpy as np

randcountry = random.choice(lsitofcountr)
listofcountr = np.array(listofcountr)
pop_distance = abs(listofcountr - randcountry)
five_closest = np.sort(pop_distance)[1:6]

相关问题 更多 >