我试图循环并基于另一个数据框创建新的数据框。假设我有这样的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
你可以检查demo.ix的值[I,J] – galaxyan