pandas Python:不支持 / 的操作数类型:'tuple' 和 'float'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29931774/
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
Python: unsupported operand type(s) for /: 'tuple' and 'float'
提问by Minh Mai
I'm trying to loop and create a new data frame based on another data frame I have. Suppose I have a dataframe like this
我正在尝试根据我拥有的另一个数据框循环并创建一个新的数据框。假设我有一个这样的数据框
Foo Fizz Buzz totals scale
10 3 2 15 .2
8 4 3 15 .2
5 1 5 11 .4
6 7 5 18 .1
9 2 6 17 .1
And a categorical variable as such:
和这样的分类变量:
groups = pd.Series(['Foo','Fizz','Buzz'], dtype = "category")
And I want to create a new dataframe where it takes the percentage of the total and multiply it by the scale. I figured the easiest way is to loop it so I can have the dataframe and names consistent but it's throwing me this error:
我想创建一个新的数据框,它取总数的百分比并将其乘以比例。我认为最简单的方法是循环它,这样我就可以让数据框和名称保持一致,但它给我带来了这个错误:
TypeError: unsupported operand type(s) for /: 'tuple' and 'float'
The code I used is below. Any help would be appreciated (I know there has to be an easier way). Thanks!
我使用的代码如下。任何帮助将不胜感激(我知道必须有更简单的方法)。谢谢!
df = pd.DataFrame() #creating an empty data frame
for j in Categorical(groups).categories: #looping through categories
calc = [] #empty list
for i in range(0, demo.shape[0]): #loop through rows
#Below is basically the column divided by the total and multiplied by the scale.
#Then take that number and append it onto the list
calc.append(round((round(cross.ix[i,j],4)/round(cross.totals[i],4)) * cross.weight[i],4))
#finally append this list to the dataframe using the categories as the column name using setting with enlargement
df.loc[:,Categorical(groups).categories[j]] = calc
回答by TigerhawkT3
round( (demo.ix[i,j],4) / round(demo.totals[i],4) )
I've added spaces to your code to emphasize what's happening: you have a tupleof demo.ix[i,j]for one element and 4for the other, then you divide that tupleby demo.totals[i]rounded to 4 places (a float), then you round that... only you can't round that because attempting to divide that tupleby a floatgives the error you saw. Try the following instead.
我已经添加空格你的代码,强调发生的事情:你有一个tuple的demo.ix[i,j]一个元素,4其他的,那么你除以tuple按demo.totals[i]四舍五入到4位(A float),那么你就圆滚滚的......只有你四舍五入,因为试图将其tuple除以 afloat会给出您看到的错误。请尝试以下操作。
round(demo.ix[i,j],4) / round(demo.totals[i],4)

