Reputation: 9213
I had a multi-index dataframe with three levels on index. I would like to multiply each Percent value by the total population.
I am trying something like this:
df = df.reset_index(level=2, drop=True)
df['TOTAL'] = df['POP.'] * output['PERCENT']
I get KeyError: 'POP.'
Starting 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
Desired Output
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
Upvotes: 2
Views: 1627
Reputation: 210852
you can use DataFrame.eval() method:
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
Upvotes: 2
Reputation: 950
You can also use multiply
method and set axis="index"
as follows:
df['TOTAL'] = df['POP'].multiply(df['PERCENT'], axis="index")
Upvotes: 2
Reputation: 323286
You need get_level_values
+ values
df['TOTAL']=(df.index.get_level_values('POP')*df['PERCENT']).values
df
Out[874]:
PERCENT TOTAL
DATE POP SEX
2015-01-01 100 MALE 0.51 51.0
FEMALE 0.49 49.0
2016-01-01 120 Male 0.52 62.4
FEMALE 0.48 57.6
Upvotes: 5