创建一个遍历数据帧行的函数,应用一个scipy函数,将输出附加到新列并输出修改后的数据帧

问题描述 投票:0回答:2

如果这个问题似乎重复了,请原谅我,但我找不到符合我确切要求的答案:

我有一个z分数的数据框,名为“ df”,其结构如下:

    score_1 score_2 score_3 score_4
1   0.15    0.20    0.81    0.60
2   0.70    0.55    0.84    0.50
3   0.90    0.33    0.54    0.07

我想创建一个新列“ z_score_combined”,其中包含每行的合并z得分。

在这种情况下,将使用scipy.stats中的“ combine_pvalues”函数合并z分数。 有关更多信息,请阅读:https://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.combine_pvalues.html

该函数的结构如下:

combine_pvalues(z-score-array, method='stouffer', weights=None)

在函数中,“ z分数数组”是每行中z分数的数组。例如,“ array_1”将是“ df”中索引为1的行中z分数的数组;即array_1 = [(0.15,0.20,0.81,0.60)],array_2 = [(0.70,0.55,0.84,0.50)]依此类推。

我将如何创建一个辅助函数:

  1. 遍历数据帧的行“ df”;
  2. 创建一维Numpy数组对象,“ z-score-array”;
  3. 将数组输入到函数中:Combine_pvalues(z-score-array,method ='stouffer',weights = None),用于计算合并的z_score;
  4. 将组合的z分数追加到数据帧“ df”中的“ z_score_combined”新列中;
  5. 输出带有合并的z分数的新列的变更版本数据帧“ df”。

谢谢你!

python pandas numpy scipy helper
2个回答
1
投票

与lambda函数一起使用DataFrame.apply,如果要一列选择元组的第一个DataFrame.apply或第二个值[0]

[1]

如果要在2列中输出2个值,请添加参数from scipy.stats import combine_pvalues df['pval'] = df.apply(lambda x: combine_pvalues(x, method='stouffer', weights=None)[1], axis=1) print (df) score_1 score_2 score_3 score_4 pval 1 0.15 0.20 0.81 0.60 0.354423 2 0.70 0.55 0.84 0.50 0.794535 3 0.90 0.33 0.54 0.07 0.394789

result_type='expand'

0
投票

尝试from scipy.stats import combine_pvalues f = lambda x: combine_pvalues(x, method='stouffer', weights=None) df[['stat','pval']] = df.apply(f, axis=1, result_type='expand') print (df) score_1 score_2 score_3 score_4 stat pval 1 0.15 0.20 0.81 0.60 0.373406 0.354423 2 0.70 0.55 0.84 0.50 -0.822260 0.794535 3 0.90 0.33 0.54 0.07 0.266859 0.394789 。您可以创建一个接受一行的函数,并且每一行都可以访问1-4列中的属性。由于您要遍历这些行,因此无需为zscores创建数组。该函数应返回该行应在combined_z_score列中输入的值。然后创建新列为:

df ['new_column'] = df.apply(您的函数,轴= 1)

© www.soinside.com 2019 - 2024. All rights reserved.