Python - Pandas 数据操作来计算基尼系数

标签 python python-3.x pandas data-science

我有以下形状的数据集:

tconst  GreaterEuropean British WestEuropean    Italian French  Jewish  Germanic    Nordic  Asian   GreaterEastAsian    Japanese    Hispanic    GreaterAfrican  Africans    EastAsian   Muslim  IndianSubContinent  total_ethnicities
0   tt0000001   3   1   2   0   1   0   0   1   0   0   0   0   0   0   0   0   0   8
1   tt0000002   2   0   2   0   2   0   0   0   0   0   0   0   0   0   0   0   0   6
2   tt0000003   4   0   3   0   3   1   0   0   0   0   0   0   0   0   0   0   0   11
3   tt0000004   2   0   2   0   2   0   0   0   0   0   0   0   0   0   0   0   0   6
4   tt0000005   3   2   1   0   0   0   1   0   0   0   0   0   0   0   0   0   0   7

这是 IMDB 数据,经过处理后,我创建了这些列,代表一部电影中有这么多民族 Actor (tcons)。

我想创建另一列df["diversity"],它是:

(多样性得分“基尼指数”)

例如: 对于每部电影,假设我们有 10 位 Actor ; 3 名亚洲人、3 名英国人、3 名非裔美国人和 1 名法国人。所以我们除以总数 3/10 3/10 3/10 1/10 然后 1 减去 ( 3/10 ) 平方的和 ( 3/10) 平方 ( 3/10) 平方 (1/10) 平方 将每个 Actor 的分数作为多样性添加到列中。

我正在尝试简单的 pandas 操作,但没有成功。

编辑:

对于第一行, 我们的种族总数为 8

3 GreaterEuropean
1 British
2 WestEuropean
1 French
1 nordic

所以分数会是

1- [(3/8)^2 + (1/8)^2 + (2/8)^2 + (1/8)^2 + (1/8)^2]

最佳答案

您可以在这里使用 numpy 向量化,即

one = df.drop(['total_ethnicities'],1).values
# Select the values other than total_ethnicities
two = df['total_ethnicities'].values[:,None]
# Select the values of total_ethnicities
df['diversity'] = 1 - pd.np.sum((one/two)**2, axis=1)
# Divide the values of one by two, square them. Sum over the axis. Then subtract from 1. 
df['diversity']

tconst
tt0000001    0.750000
tt0000002    0.666667
tt0000003    0.710744
tt0000004    0.666667
tt0000005    0.693878
Name: diversity, dtype: float64

关于Python - Pandas 数据操作来计算基尼系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48559991/

相关文章:

python - 调用一个字符串类型的类属性

python - Plotly:如何交替背景网格颜色?

python - Dataframe 将 float 转换为全小数的字符串

python - 比使用大数据集申请更快的方式来完成这个 Pandas 工作?

python:循环遍历Excel中的索引并用字符串替换

python-3.x - Pyinstaller:语法错误:位置参数跟随关键字参数

python - 字符串连接的变体?

python - 来自嵌套单词列表的共现矩阵

Python:在满足特定条件时跳过代码块(计算)而不使用 "if"语句

python - Python 中的 Soap 调用