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

标签 python python-3.x pandas

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

我尝试过使用 .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/

相关文章:

python - 如何删除数据框的所有列都等于 None 的每一行

python - 在具有多个条件的 Pandas 中复制 Countifs()

python-3.x - 在 Python 中转置和乘法列表

python - 如何使用 Python 在 Raspberry Pi 上列出 I2C 地址?

python - 如何禁用 tqdm 的进度条并仅保留 Pytorch Lightning(或一般的 tqdm)中的文本信息

python - 如何动态更改 pytest 的 tmpdir 基本目录

python - 运行存储在列表中的各个 python import 语句

当我尝试保存文件时 Python 3.2 崩溃

python-3.x - Pandas 读取一个文本文件并根据第一个字符将名称分成几列

python - 为什么我的 if 语句在 while 循环中不起作用?