Pandas 如何将输出的多个值分配给数据帧的新多列?
我有以下功能:Pandas 如何将输出的多个值分配给数据帧的新多列?,pandas,apply,Pandas,Apply,我有以下功能: def sum(x): oneS = x.iloc[0:len(x)//10].agg('sum') twoS = x.iloc[len(x)//10:2*len(x)//10].agg('sum') threeS = x.iloc[2*len(x)//10:3*len(x)//10].agg('sum') fourS = x.iloc[3*len(x)//10:4*len(x)//10].agg('sum') fiveS = x.iloc
def sum(x):
oneS = x.iloc[0:len(x)//10].agg('sum')
twoS = x.iloc[len(x)//10:2*len(x)//10].agg('sum')
threeS = x.iloc[2*len(x)//10:3*len(x)//10].agg('sum')
fourS = x.iloc[3*len(x)//10:4*len(x)//10].agg('sum')
fiveS = x.iloc[4*len(x)//10:5*len(x)//10].agg('sum')
sixS = x.iloc[5*len(x)//10:6*len(x)//10].agg('sum')
sevenS = x.iloc[6*len(x)//10:7*len(x)//10].agg('sum')
eightS = x.iloc[7*len(x)//10:8*len(x)//10].agg('sum')
nineS = x.iloc[8*len(x)//10:9*len(x)//10].agg('sum')
tenS = x.iloc[9*len(x)//10:len(x)//10].agg('sum')
return [oneS,twoS,threeS,fourS,fiveS,sixS,sevenS,eightS,nineS,tenS]
如何将此函数的输出分配给dataframe(已存在)的列
我应用该函数的数据帧如下所示
Cycle Type Time
1 1 101
1 1 102
1 1 103
1 1 104
1 1 105
1 1 106
9 1 101
9 1 102
9 1 103
9 1 104
9 1 105
9 1 106
我想要添加列的数据框如下所示&新列一、二。。。。。应添加如图所示并填充函数结果
Cycle Type OneS TwoS ThreeS
1 1
9 1
8 1
10 1
3 1
5 2
6 2
7 2
如果我只为一个值编写一个函数,并按如下方式应用它,则有可能:
grouped_data['fm']= data_train_bel1800.groupby(['Cycle', 'Type'])['Time'].apply( lambda x: fm(x))
但我想一次完成所有操作,使其整洁清晰。您可以使用:
def f(x):
out = []
for i in range(10):
out.append(x.iloc[i*len(x)//10:(i+1)*len(x)//10].agg('sum'))
return pd.Series(out)
df1 = (data_train_bel1800.groupby(['Cycle', 'Type'])['Time']
.apply(f)
.unstack()
.add_prefix('new_')
.reset_index())
print (df1)
Cycle Type new_0 new_1 new_2 new_3 new_4 new_5 new_6 new_7 new_8 \
0 1 1 0 101 102 205 207 209 315 211 211
1 9 1 0 101 102 205 207 209 315 211 211
new_9
0 106
1 106
@AndyHayden-oops,您是对的,答案已更改。应将新列添加到seprate数据帧(该数据帧已存在,并且只有少数列具有“分组”值)中,而不是添加到原始数据帧中。在我的问题中,我已经展示了我正在应用函数的df&我想在其中添加结果的df。第一个解决方案起作用了,但它创建了一个名为“groupeddata”的新df&因此该数据帧中的现有值都受到了干扰&正在查找wierd@mohanys-不确定是否理解,请检查编辑的答案。我只需要为每个分组项目设置一行,即1,1和9,1设置一行。结果应该与您在第一个答案中所做的相同(将结果添加到数据中)。因此,应该添加10列,并将函数的输出分配给每列。因此,根据我发布的数据,分组的_数据df将是shape 2,12这是有效的。然而,在我的例子中,df1已经存在,因此新的值没有添加到该值中,但是如果df1不存在,它工作正常。因此,我将其作为代码的文件行(这样创建df1),但无法向其添加列。例如,我的代码
df1['mean']=data\u train\u bel1800.groupby(['Cycle','Type'])['Detrended'].mean()
抛出错误“TypeError:插入列的索引与框架索引不兼容”