Pandas 定义在不同数据帧中创建新列时要调用的 Z_score 函数

Posted

技术标签:

【中文标题】Pandas 定义在不同数据帧中创建新列时要调用的 Z_score 函数【英文标题】:Pandas defining Z_score function to be called when creating new columns in different dataframes 【发布时间】:2021-03-12 12:29:51 【问题描述】:
def z_score(df, column, mean, std):
    return #  ?????

mean = history_df['distances'].mean()
std = history_df['distances'].std()
training_df['distances_normal'] = z_score(training_df, 'distances', mean, std)
testing_df['distances_normal'] = z_score(testing_df, 'distances', mean, std)

你好,关于 z_score 函数应该是什么样子(返回后)的任何建议,以便在我根据历史数据帧列“距离”创建新列“距离正常”到训练和测试数据帧时进一步向下,值是归一化?

提前谢谢

【问题讨论】:

【参考方案1】:

不需要定义z_score函数,计算简单,直接在dateframe上进行即可:

training_df['distances_normal'] = (training_df['distances'] - mean)/ std

如果您仍然想使用z_score 函数,那么您可以定义它一次取一个元素,然后使用apply 依次将其应用于数据框列的每个元素:

def z_score(x, mean, std):
    return (x - mean)/std

training_df['distances_normal'] = training_df['distances'].apply(lambda x: z_score(x, mean, std))

最终结果是一样的,但第一个版本更快,因为它使用向量运算

您也可以为此使用一些标准库工具,因为它很常见,请参阅例如this question

【讨论】:

以上是关于Pandas 定义在不同数据帧中创建新列时要调用的 Z_score 函数的主要内容,如果未能解决你的问题,请参考以下文章