Pandas MultiIndex:将所有列除以一列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29354553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas MultiIndex: Divide all columns by one column
提问by FooBar
I have a data frame resultsof the form
我有一个results表单的数据框
TOTEXPPQ TOTEXPCQ FINLWT21
year quarter
13 1 9.183392e+09 5.459961e+09 1271559.398
2 2.907887e+09 1.834126e+09 481169.672
and I was trying to divide all (the first two) columns by the last one. My attempt was
我试图将所有(前两列)列除以最后一列。我的尝试是
weights = results.pop('FINLWT21')
results/weights
But I get
但我得到
ValueError: cannot join with no level specified and no overlapping names
Which I don't get: There are overlapping names in the index:
我没有得到:索引中有重叠的名称:
weights.head()
year quarter
13 1 1271559.398
2 481169.672
Is there perhaps a better way to do this division? Do I needto reset the index?
也许有更好的方法来进行这种划分?我需要重置索引吗?
回答by Andy Hayden
You have to specify the axis for the divide (with the divmethod):
您必须指定除法轴(使用div方法):
In [11]: results.div(weights, axis=0)
Out[11]:
TOTEXPPQ TOTEXPCQ
year quarter
13 1 7222.149445 4293.909517
2 6043.371329 3811.807158
The default is axis=1 and the result columnsand weights' index names do not overlap, hence the error message.
默认值为 axis=1 并且结果列和权重的索引名称不重叠,因此会出现错误消息。

