首页 > 解决方案 > 条件差异,除以数据框熊猫的同一列

问题描述

嗨希望得到一些帮助,我有一个这样的 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 值。但这有点讨厌,考虑到大熊猫通常在这些事情上有多好。这样做的内置方法是什么?

标签: pythonpython-3.xpandaspandas-groupby

解决方案


在我看来,这里最好DataFrame单独使用每个 - 所以首先按条件过滤DataFrame.pop提取列,MultiIndex按列创建对齐并为所有值应用公式。然后添加DataFrame.add_suffixandDataFrame.jointestDataFrame 并最后如果需要一个 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

推荐阅读