微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python – Pandas数据操作来计算Gini系数

我有数据集,其形状如下:

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数据,经过处理后,我创建了这些列,代表电影中有很多民族演员(tcons).

我想创建另一个列df [“diversity”],它是:

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

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

我正在尝试简单的熊猫操纵,但没有到达那里.

编辑:

对于第一行,
我们的总种族数为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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐