首页 > 解决方案 > 根据逐行操作添加新的 pandas df 列

问题描述

我有一个这样的数据框:

Interesting           genre_1        probabilities
    1    no            Empty        0.251306
    2    yes           Empty        0.042043
    3     no          Alternative    5.871099
    4    yes         Alternative    5.723896
    5    no           Blues         0.027028
    6    yes          Blues         0.120248
    7    no          Children's     0.207213
    8    yes         Children's     0.426679
    9    no          Classical      0.306316
    10    yes         Classical      1.044135

我想根据有趣的列对同一类别执行 GINI 索引。之后,我想在新的 pandas 列中添加这样的值。

这是获取基尼指数的函数:

#Gini Function
#a and b are the quantities of each class
def gini(a,b):
    a1 = (a/(a+b))**2
    b1 = (b/(a+b))**2
    return 1 - (a1 + b1) 

编辑* 抱歉,我的最终所需数据框中有错误。在选择 prob(A) 和 prob(B) 时,是否有趣并不重要,但 Gini 分数将是相同的,因为它将衡量我们将多少杂质归类为有趣或不有趣的歌曲。因此,如果概率在 50/50% 左右,则意味着 Gini 分数将达到最大值(0.5),这是因为同样可能会被错误地选择是否有趣。

所以对于前两行,基尼指数将是:

a=no; b=Empty -> gini(0.251306, 0.042043)= 0.245559831601612
a=yes; b=Empty -> gini(0.042043, 0.251306)= 0.245559831601612

然后我想得到类似的东西:

 Interesting           genre_1        percentages.  GINI INDEX
        1    no            Empty        0.251306         0.245559831601612
        2    yes           Empty        0.042043         0.245559831601612
        3     no          Alternative    5.871099         0.4999194135183881
        4    yes         Alternative    5.723896.     0.4999194135183881
        5    no           Blues         0.027028          ..
        6    yes          Blues         0.120248
        7    no          Children's     0.207213
        8    yes         Children's     0.426679
        9    no          Classical      0.306316          ..
        10    yes         Classical      1.044135         ..

标签: pythonpandasgini

解决方案


我不确定该Interesting列是如何影响所有这些的,但我强烈建议您使用numpy.where(). 语法类似于:

import numpy as np
df['GINI INDEX'] = np.where(__condition__,__what to do if true__,__what to do if false__)

推荐阅读