2015-04-28 91 views
0

我试图循环并基于另一个数据框创建新的数据框。假设我有这样的Python:不支持的操作数类型为/:'tuple'和'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 
+0

你可以检查demo.ix的值[I,J] – galaxyan

回答

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

我添加空格你的代码,强调发生的事情:你有demo.ix[i,j]一个tuple了一个元素和4为其他,那么你除以tuple通过demo.totals[i]四舍五入到4个地方(一个float),那么你围绕...只有你不能这样做,因为试图将tuple除以float给出了你所看到的错误。改为尝试以下内容。

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

所以我试图用 'calc.append(圆(demo.ix [I,J]您的建议,4)/轮(演示.totals [i],4)* demo.scale [i])' 和我得到一个错误东西沿着这些线 'pandas/hashtable.pyx在pandas.hashtable.Int64HashTable.get_item(pandas/hashtable.c :7193)()' 'KeyError:3' –

+0

其实,没关系,我看你想要解释什么。谢谢! –

相关问题