我有一个数据帧:
import pandas as pd
import numpy as np
df = pd.DataFrame([['M',2014,'Seth',5],
['M',2014,'Spencer',5],
['M',2014,'Tyce',5],
['F',2014,'Seth',25],
['F',2014,'Spencer',23]],columns =['sex','year','name','number'])
print df
我想找出2014年最具性别模糊性的名字。我试过很多方法,但还没有一点运气。在
注意:我确实在答案的末尾写了一个函数,但是为了更好地理解,我决定一部分一部分地运行代码
获取性别模糊的名字
首先,你需要得到性别模糊的名字列表。我建议使用集合交集:
现在,你想把数据子集化,在2014年只显示性别不明确的名字。您需要使用成员条件,并将布尔条件作为一行程序进行链接:
^{pr2}$聚合数据
现在您将其命名为
gender_ambiguous_data_2014
:然后你只需按数字汇总:
正在提取名称
现在,你最不希望得到的是数字最高的名字。但实际上,你可能有性别模糊的名字,它们的总数相同。我们应该将前面的结果应用到一个新变量
gender_ambiguous_numbers_2014
并使用它:现在你得到这个:
好吧,让我们提取索引名吧!在
等等,这是什么类型的?(提示:它是
pandas.core.index.Index
)没问题,只需应用列表强制:
让我们把这个写在一个函数里!在
所以,在本例中,我们的列表只有元素。但是也许我们想写一个函数,它返回一个字符串作为唯一的竞争者,或者返回一个字符串列表,如果一些性别不明确的名字在那一年有相同的总数。在
在下面的包装器函数中,我用
ga
来缩短代码。当然,这是假设数据集的格式与您所显示的格式相同,并且命名为df
。如果它是以其他方式命名的,只需相应地更改df
。在现在,调用此函数非常简单:
不知道你说的“最性别矛盾”是什么意思,但你可以从这里开始
如果您只想得到总数最高的名字,那么:
^{pr2}$相关问题 更多 >
编程相关推荐