Python Pandas 当我在现有数据框中添加一列时,我的新列不正确

Python Pandas when i add a column in an existing dataframe my new column is not correct

我正在尝试完成一个宗教信仰数据可视化项目。但是我一直被这个问题困扰着,请帮忙谢谢

    x= range(1945,2011,5)
    for i in x:
       df_new= df_new.append(pd.DataFrame({'year':[i]}))
    

    years
0   1945
0   1950
0   1955
0   1960
0   1965
0   1970
0   1975
0   1980
0   1985
0   1990
0   1995
0   2000
0   2005
0   2010

这是我现在的数据框,我想添加一个如下所示的列:

0     1.307603e+08
1     2.941211e+08
2     3.440720e+08
3     4.351231e+08
4     5.146341e+08
5     5.923423e+08
6     6.636743e+08
7     6.471395e+08
8     7.457716e+08
9     9.986003e+08
10    1.153186e+09
11    1.314048e+09
12    1.426454e+09
13    1.555483e+09

当我这样加起来的时候

a=df.groupby(['year'],as_index=False)['islam'].sum()
b=a['islam']
df_new.insert(1,'islam',b)

数据框看起来像这样不正确请帮助我谢谢!

    year    islam
0   1945    130760281.0
0   1950    130760281.0
0   1955    130760281.0
0   1960    130760281.0
0   1965    130760281.0
0   1970    130760281.0
0   1975    130760281.0
0   1980    130760281.0
0   1985    130760281.0
0   1990    130760281.0
0   1995    130760281.0
0   2000    130760281.0
0   2005    130760281.0
0   2010    130760281.0

df:

    year    name    christianity    judaism islam   budism  nonrelig
0   1945    USA 110265118   4641182.0   0.0 1601218 22874544
1   1950    USA 122994019   6090837.0   0.0 0   22568130
2   1955    USA 134001770   5333332.0   0.0 90173   23303540
3   1960    USA 150234347   5500000.0   0.0 2012131 21548225
4   1965    USA 167515758   5600000.0   0.0 1080892 19852362
... ... ... ... ... ... ... ...
1990 1990   WSM 159500  0.0 37.0    15  1200
1991 1995   WSM 161677  0.0 43.0    16  1084
1992 2000   WSM 174600  0.0 50.0    18  1500
1993 2005   WSM 177510  0.0 58.0    18  1525
1994 2010   WSM 180140  0.0 61.0    19  2750

如果列表的长度与DataFrame的长度相同并且值的顺序符合要求,则可以直接将列分配给DataFrame

islam_values = [
    1.307603e+08,
    2.941211e+08,
    3.440720e+08,
    4.351231e+08,
    5.146341e+08,
    5.923423e+08,
    6.636743e+08,
    6.471395e+08,
    7.457716e+08,
    9.986003e+08,
    1.153186e+09,
    1.314048e+09,
    1.426454e+09,
    1.555483e+09,
]

df = pd.DataFrame({'year': list(range(1945, 2011, 5))})
df["islam"] = islam_values

输出

    year    islam
0   1945    1.307603e+08
1   1950    2.941211e+08
2   1955    3.440720e+08
3   1960    4.351231e+08
4   1965    5.146341e+08
5   1970    5.923423e+08
6   1975    6.636743e+08
7   1980    6.471395e+08
8   1985    7.457716e+08
9   1990    9.986003e+08
10  1995    1.153186e+09
11  2000    1.314048e+09
12  2005    1.426454e+09
13  2010    1.555483e+09