python - 条件差异,除以数据框熊猫的同一列
问题描述
嗨希望得到一些帮助,我有一个这样的 Dataframe df:
label cell_name hour kpi1 kpi2
train c1 1 10 20
train c1 2 10 44
train c1 3 11 33
train c1 4 5 1
train c1 5 2 6
test c1 1 78 66
test c1 2 45 2
test c1 3 23 12
test c1 4 65 45
test c1 5 86 76
我的意图是有条件地从测试集的 kpi1,kpi2 列中减去一些值让我们说(50),并用训练集(groupby cell & hour)划分相同的列并将其附加到原始数据框,以便新列将看起来像;
label cell_name hour kpi1 kpi2 kpi1_index kpi2_index
train c1 1 10 20
train c1 2 10 44
train c1 3 11 33
train c1 4 5 1
train c1 5 2 6
test c1 1 78 66 2.8 0.8
test c1 2 45 2 -0.5 -1.09
test c1 3 23 12 -2.45 -1.15
test c1 4 65 45 3 -5
test c1 5 86 76 18 4.33
我尝试了以下代码:
import pandas as pd
import os
rr=os.getcwd()
df=pd.read_excel(rr+'\\KPI_test_train.xlsx')
print(df.columns)
def f(x,y):
return ((x-50)/y)
df_grouped = df.groupby(['label'])
[dtest,dtrain]=[y for x,y in df_grouped]
dtest=dtest.groupby(['label','cell_name','hour']).sum()
dtrain=dtrain.groupby(['label','cell_name','hour']).sum()
for i in dtest.columns:
dtest[i+'_index']=f(dtest[i],dtrain[i])
函数 f 返回所有行的 NaN 值。但这有点讨厌,考虑到大熊猫通常在这些事情上有多好。这样做的内置方法是什么?
解决方案
在我看来,这里最好DataFrame
单独使用每个 - 所以首先按条件过滤DataFrame.pop
提取列,MultiIndex
按列创建对齐并为所有值应用公式。然后添加DataFrame.add_suffix
andDataFrame.join
到test
DataFrame 并最后如果需要一个 DataFrame 使用concat
:
lab = df.pop('label')
dtest = df[lab.eq('train')].set_index(['cell_name','hour'])
dtrain = df[lab.eq('test')].set_index(['cell_name','hour'])
df = dtest.join(((dtrain - 50) / dtest).add_suffix('_index'))
df = (pd.concat([dtrain, df], keys=('train','test'), sort=False)
.reset_index()
.rename(columns={'level_0':'label'}))
print (df)
label cell_name hour kpi1 kpi2 kpi1_index kpi2_index
0 train c1 1 78 66 NaN NaN
1 train c1 2 45 2 NaN NaN
2 train c1 3 23 12 NaN NaN
3 train c1 4 65 45 NaN NaN
4 train c1 5 86 76 NaN NaN
5 test c1 1 10 20 2.800000 0.800000
6 test c1 2 10 44 -0.500000 -1.090909
7 test c1 3 11 33 -2.454545 -1.151515
8 test c1 4 5 1 3.000000 -5.000000
9 test c1 5 2 6 18.000000 4.333333
推荐阅读
- c# - ListViews的ItemsControl,从每个ListViews中绑定SelectedItem,其中ListViews的数量是动态的,MVVM
- ios - 按返回键时输入附件视图错位
- java - 如何启用基于 Spring Boot 配置文件的测试?
- java - spring webflux如何创建会话
- javascript - 点击提交按钮后,如何将使用多种类型输入值创建的表格从表单显示到另一个页面?
- angular - 无法以角度运行 toast 消息的单元测试用例
- java - 我该怎么做才能为下面的代码创建单元测试
- windows - 在 QT 程序中全局强制 QFileDialog::DontUseNativeDialog
- c++ - 作为参数引用
- java - 从 ArrayList (java) 中获取元素