numpy 如何根据以前行的计算创建新行?

snvhrwxg  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(60)

我正在处理一个数据库,其中有6列:经济,亚行代码,年份,部门,就业指数,VA指数.在行中,存在具有相应年份的值的所有国家。问题是我需要创建一个新的行扇区,它将由其他扇区的总和组成。Here's an example in excel
我试着计算指数的值,我认为这是成功的。代码如下:

construction = df.query("Sector == 'Construction'")
manufacturing = df.query("Sector == 'Manufacturing'")
mining_utilities = df.query("Sector == 'Mining, Utilities'")

#turning the dataframes from aboove into numpy arrays to calculate the values more easily
construction_array = construction.to_numpy()

manufacturing_array = manufacturing.to_numpy()

mining_utilities_array = mining_utilities.to_numpy()

#calculating values for the new variable
industry_array = construction_array + manufacturing_array + mining_utilities_array

industry_array

字符串
问题是,我不知道如何正确地将这个数组集成到数据库中,因为我缺少所有其他列的值。
我也试过用字典来做这件事,但结果变得很混乱,所以我决定不使用那个选项

83qze16e

83qze16e1#

以下是你想要做的事情(基于屏幕截图):

import pandas as pd

df = pd.DataFrame({
    "Year" : [2016, 2016, 2016],
    "Sector" : ["Mining", "Agriculture", "Manufacturing"],
    "Employment Index" : [0.5, 0.6, 0.7],
    "VA Index" : [0.4, 0.5, 0.6]
})
emp_index = (df.pivot(index="Year", columns="Sector", values="Employment Index")
             .assign(Total = lambda x: x.sum(axis=1)))

va_index = (df.pivot(index="Year", columns="Sector", values="VA Index")
            .assign(Total = lambda x: x.sum(axis=1)))

emp_index
Sector  Agriculture  Manufacturing  Mining  Total
Year                                             
2016            0.6            0.7     0.5    1.8

va_index
Sector  Agriculture  Manufacturing  Mining  Total
Year                                             
2016            0.5            0.6     0.4    1.5

字符串
如果不是,请发布预期的输出,沿着一个可复制的示例。

相关问题