将Pandas列乘以多索引值

时间:2018-01-12 23:50:49

标签: python python-2.7 pandas

我有一个多索引数据框,索引上有三个级别。我想将每个百分比值乘以总人口。

我正在尝试这样的事情:

df = df.reset_index(level=2, drop=True)
df['TOTAL'] = df['POP.'] * output['PERCENT']

我得到KeyError: 'POP.'

启动DataFrame

                               PERCENT  
     DATE      POP.  SEX                
2015-01-01     100  MALE        0.51  
                    FEMALE      0.49  
2016-01-01     200  MALE        0.52  
                    FEMALE      0.48

期望输出

                               PERCENT     TOTAL  
     DATE      POP.  SEX                
2015-01-01     100  MALE        0.51         51  
                    FEMALE      0.49         49
2016-01-01     200  MALE        0.52        104
                    FEMALE      0.48         96

3 个答案:

答案 0 :(得分:4)

您需要public string LastNameFirstName { get { return lastName + ", " + firstName; } } + get_level_values

values

答案 1 :(得分:3)

您还可以使用multiply方法并设置axis="index",如下所示:

df['TOTAL'] = df['POP'].multiply(df['PERCENT'], axis="index")

答案 2 :(得分:2)

您可以使用DataFrame.eval()方法:

In [118]: df = df.eval("TOTAL = PERCENT * POP", inplace=False)

In [119]: df
Out[119]:
                         PERCENT  TOTAL
DATE       POP   SEX
2015-01-01 100.0 MALE       0.51   51.0
                 FEMALE     0.49   49.0
2016-01-01 200.0 MALE       0.52  104.0
                 FEMALE     0.48   96.0