繁体   English   中英

Python:/:'tuple'和'float'不支持的操作数类型

[英]Python: unsupported operand type(s) for /: 'tuple' and 'float'

我试图循环并基于我拥有的另一个数据框创建一个新的数据框。 假设我有一个像这样的数据框

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

和这样的分类变量:

groups = pd.Series(['Foo','Fizz','Buzz'], dtype = "category")

我想创建一个新的数据框,该框将占总数的百分比乘以比例。 我认为最简单的方法是循环它,这样我就可以使数据框和名称保持一致,但这会引发以下错误:

TypeError: unsupported operand type(s) for /: 'tuple' and 'float'

我使用的代码如下。 任何帮助将不胜感激(我知道必须有一个更简单的方法)。 谢谢!

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 
round(   (demo.ix[i,j],4) / round(demo.totals[i],4)   )

我在代码中添加了空格,以强调发生的事情:一个元素有一个demo.ix[i,j] tuple ,另一个元素有4 tuple ,然后用demo.totals[i]将该tuple除以4放置(一个float ),然后四舍五入...只能四舍五入,因为尝试将tuple除以float会产生您看到的错误。 请尝试以下方法。

round(demo.ix[i,j],4) / round(demo.totals[i],4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM