gpt4 book ai didi

python - 使用迭代器作为列和索引更快地将总和值附加到数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:30 25 4
gpt4 key购买 nike

我想知道一种最快、最干净的方法来编写代码,将我的求和值附加到新的空数据帧。

我尝试过使用 .sum() 和 sum() 以及 pandas 系列和 apply()。

但我想确认我是否处于最佳状态,可以在这里编写最干净、最快的代码。如果两者不能同时实现,我宁愿最快。

更干净意味着这里的代码更具可读性或可重用性。这对我来说是一个困惑的代码。它按我的意愿工作,但我想要一个比这更快的解决方案。

df_year = pd.DataFrame()
for i in range(1960,2018,1):
df_year[str(i)] = pd.Series(sum(df_indicator[str(i)]))

所有三个国家的样本数据如下:

df_指示器

    Country Name    Country Code    Indicator Name  Indicator Code  1960    1961    1962    1963    1964    1965    1966    1967
33 Canada CAN Population, total SP.POP.TOTL 17909009.0 18271000.0 18614000.0 18964000.0 19325000.0 19678000.0 20048000.0 20412000.0
152 Mexico MEX Population, total SP.POP.TOTL 38174112.0 39394126.0 40649588.0 41939880.0 43264272.0 44623043.0 46011038.0 47429812.0
249 United States USA Population, total SP.POP.TOTL 180671000.0 183691000.0 186538000.0 189242000.0 191889000.0 194303000.0 196560000.0 198712000.0

最佳答案

我认为这就是您想要做的:

In [1]: from pandas import DataFrame

In [2]: df = DataFrame({'Country': ['US', 'Canada', 'Mexico', 'Belize'], '1960': range(4), '1961': range(10, 14)})

In [3]: df
Out[3]:
Country 1960 1961
0 US 0 10
1 Canada 1 11
2 Mexico 2 12
3 Belize 3 13

In [4]: res = df[df['Country'].isin(['US', 'Canada'])].sum()

In [5]: res
Out[5]:
Country USCanada
1960 1
1961 21
dtype: object

显然,您可以操纵结果系列来满足您的需求:

In [6]: df_year = DataFrame(df[df['Country'].isin(['US', 'Canada'])].sum()).transpose().drop(['Country'], inplace=True, axis=1)

In [7]: df_year.drop(['Country'], inplace=True, axis=1)

In [8]: df_year
Out[8]:
1960 1961
0 1 21

关于python - 使用迭代器作为列和索引更快地将总和值附加到数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58003022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com