簡體   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