gpt4 book ai didi

python - 在 Pandas 的测试数据框中查找数据的 z 分数

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:42 25 4
gpt4 key购买 nike

我有分组的数据,分为训练集和测试集。我正在寻找计算 z 分数。在训练集上,这很容易,因为我可以使用内置函数来计算均值和标准差。

这是一个示例,我在其中按地点查找 z 分数: 将 Pandas 导入为 pd 将 numpy 导入为 np # 我的示例数据框

train = pd.DataFrame({'place':     ['Winterfell','Winterfell','Winterfell','Winterfell','Dorne', 'Dorne','Dorne'],
'temp' : [ 23 , 10 , 0 , -32, 90, 110, 100 ]})
test = pd.DataFrame({'place': ['Winterfell', 'Winterfell', 'Dorne'],
'temp' : [6, -8, 100]})

# get the z-scores by group for the training set
train.loc[: , 'z' ] = train.groupby('place')['temp'].transform(lambda x: (x - x.mean()) / x.std())

现在训练数据框采用以下形式:

|    Place   | temp |   z   |
|------------|------|-------|
| Winterfell | 23| 0.969 |
| Winterfell | 10| 0.415 |
| Winterfell | 0|-0.011 |
| Winterfell | -32|-1.374 |
| Dorne | 90| 1.000 |
| Dorne | 110|-1.000 |
| Dorne | 100| 0.000 |

这就是我想要的。

问题是我现在想使用训练集中的均值和标准差来计算测试集中的 z 分数。我可以很容易地得到平均值和标准偏差:

summary = train.groupby('place').agg({'temp' : [np.mean, np.std]} ).xs('temp',axis=1,drop_level=True)

print(summary)

mean std
place
Dorne 100.00 10.000000
Winterfell 0.25 23.471614

我有一些复杂的方法来做我想做的事情,但由于这是我必须经常做的任务,我正在寻找一种简洁的方法来做它。到目前为止,这是我尝试过的:

  1. 从汇总表中创建字典 dict,我可以在其中提取均值和标准差作为元组。然后在测试集上,我可以做一个应用:

    test.loc[: , 'z'] = test.apply(lambda row: (row.temp - dict[row.place][0]) / dict[row.place][1] ,axis = 1)

为什么我不喜欢它:

  • 字典读起来很费劲,需要知道dict的结构是什么。
  • 如果一个地方出现在测试集中但没有出现在训练集中,代码将抛出一个错误,而不是得到 NaN。

    1. 使用索引

      test.set_index('place', inplace = True)
      test.loc[:, 'z'] = (test['temp'] - summary['mean'])/summary['std']

为什么我不喜欢它: - 看起来应该可以,但只给我 NaN

最终结果应该是是否有标准的 pythonic 方式来进行这种组合?

最佳答案

选项 1
pd.Series.map

test.assign(z=
(test.temp - test.place.map(summary['mean'])) / test.place.map(summary['std'])
)

place temp z
0 Winterfell 6 0.244977
1 Winterfell -8 -0.351488
2 Dorne 100 0.000000

选项 2
pd.DataFrame.eval

test.assign(z=
test.join(summary, on='place').eval('(temp - mean) / std')
)

place temp z
0 Winterfell 6 0.244977
1 Winterfell -8 -0.351488
2 Dorne 100 0.000000

关于python - 在 Pandas 的测试数据框中查找数据的 z 分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45949160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com