我在字典中有一个dfs19_df
,如下所示:
BacksGas_Flow_sccm ContextID StepID Time_Elapsed iso_forest
61.81640625 7289972 19 40.503 -1
62.59765625 7289972 19 41.503 -1
63.671875 7289972 19 42.503 1
65.625 7289972 19 43.503 1
61.81640625 7289973 19 40.448 -1
62.59765625 7289973 19 41.448 -1
63.671875 7289973 19 42.448 1
65.625 7289973 19 43.448 1
我编写了一个函数,通过对ContextID
列执行groupby
来计算iso_forest
中+1和-1的数量,然后计算-1/1的比率:
def minus1_plus1_ratio(dictionary, new_df, step_df):
dictionary[new_df] = dictionary[step_df].groupby(['ContextID', 'iso_forest']).size().reset_index(name='count')
dictionary[new_df] = pd.pivot_table(dictionary[new_df], values = 'count', columns = ['iso_forest'],
index = ['ContextID']).fillna(value = 0)
dictionary[new_df]['-1/1'] = (dictionary[new_df][-1])/(dictionary[new_df][1])
dictionary[new_df] = dictionary[new_df].sort_values(by = '-1/1', ascending = False)
return dictionary[new_df]
因此,当我在上面的df上运行函数时
minus1_plus1_ratio(Bgf, 's19_-1/1', 's19_df')
由于iso_forest
列同时具有-1s和+1s,因此它工作得非常好
但对于df,如下所示:
BacksGas_Flow_sccm ContextID StepID Time_Elapsed iso_forest
61.81640625 7289972 19 40.503 1
62.59765625 7289972 19 41.503 1
63.671875 7289972 19 42.503 1
65.625 7289972 19 43.503 1
61.81640625 7289973 19 40.448 1
62.59765625 7289973 19 41.448 1
63.671875 7289973 19 42.448 1
65.625 7289973 19 43.448 1
如果在iso_forest
列中没有-1并且只有+1,那么运行函数会抛出一个key error: -1
,因为没有-1
所以,我想做的是,如果没有-1,那么在
dictionary[new_df]['-1/1'] = (dictionary[new_df][-1])/(dictionary[new_df][1])
步骤中,必须创建名为-1
的列,并且必须用零填充该列
类似地,在某些情况下,可能只存在-1,而不存在+1。在这种情况下,必须创建+1列并用零填充
有人能帮我解释一下逻辑吗?我怎样才能做到这一点
您可以使用
unstack
和reindex
:输出:
相关问题 更多 >
编程相关推荐