python - 根据逐行操作添加新的 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 ..
解决方案
我不确定该Interesting
列是如何影响所有这些的,但我强烈建议您使用numpy.where()
. 语法类似于:
import numpy as np
df['GINI INDEX'] = np.where(__condition__,__what to do if true__,__what to do if false__)
推荐阅读
- salesforce - 计算案例结束日期和案例创建日期之间的工作时间
- java - Quarkus 中的 Redis 和并发错误:没有 MULTI 的 ERR EXEC
- pdf - 在 Ghostscript 压缩后,带有内部链接的 PDF 在 OSX 中变得非常慢
- html - 如何将 H1 与图像对齐
- google-colaboratory - 如何将 Google Colab 的版本升级到 20 或 21?
- php - Google App Engine 标准缓存上的 Codeigniter 4 无法写入 /tmp/cache/
- excel - 返回高度与给定表相同的溢出范围
- makefile - 如何防止输出文件夹显示为可能的目标(自动完成)
- python - 使用机器人删除特定用户对 discord.py 的反应
- windows - GNU sed 4.2.1 匹配第二次出现