根据现有列中的唯一文本值创建新的 Z-Score 列

Create new Z-Score column based off unique text values in an existing column

系统:O365

IDE: JupyterLab

语言:Python版本 3.7.3

库: pandas 版本 1.0.1

数据来源:个人建

Http API 文档: https://github.com/RTICWDT/open-data-maker/blob/master/API.md

你好,我想知道是否有人知道如何 return 使用列范围内的条件设置的值。例如,我想 return z-scores 基于范围内的相似值,一旦看到下一组值就会发生变化。

采取的步骤:

  1. 构建了下面的函数,它似乎已经完成了一半,但还不完全是

代码:

# get data
df0 = pd.read_csv('data/erpservicedesk.csv')
df0.columns

# put z-score into a lamda
zscore = lambda x: (x - x.mean()) / x.std()

# build datafram with the important features
df1 = df0[['Incident ID*+', 'Res.Prod.Cat.TierII', 'Res.Op.Cat.TierIII', 'Mean-Time-Tckt-Close']]

df1.insert(4,'ZofMTTC',df1.groupby(['Res.Prod.Cat.TierII', 'Res.Op.Cat.TierIII'])['Mean-Time-Tckt-Close'].transform(zscore))

df2 = df1.sort_values(by=['Res.Prod.Cat.TierII'])
df2.head(100)

问题

看来我的 lambda 函数不是基于新列值的条件,因为它似乎对整个数据帧采用 'Mean-Time-Tckt-Close',而不是 'Res.Prod.Cat.TierII' 的每个新实例。

例子

A B C
Bob Store 10
Bob Store 11
Bob Store 8
Alfred Store 12
Alfred Store 9

我需要一个新的 D 列来反映 Bob 和 Alfred 基于他们各自数据的 Z 分数。

使用您的示例,您可以使用 .groupby 创建 dfs 来存储均值和标准差,然后在 lambda 函数中访问它们:

import pandas as pd

## recreate example df
df = pd.DataFrame({'A':['Bob']*3+['Alfred']*2, 'B':['Store']*5, 'C':[10,11,8,12,9]})

df_mean =  df.groupby('A').mean()
df_std =  df.groupby('A').std()

## apply the function along each row, using axis=1
df['D'] = df.apply(lambda x: (x['C'] - df_mean.loc[x['A']]) / df_std.loc[x['A']], axis=1)

输出:

>>> df
        A      B   C         D
0     Bob  Store  10  0.218218
1     Bob  Store  11  0.872872
2     Bob  Store   8 -1.091089
3  Alfred  Store  12  0.707107
4  Alfred  Store   9 -0.707107