我正在使用Python软件包names
来生成一些用于质量检查测试的名字。
names
软件包包含函数names.get_first_name(gender)
,该函数允许使用字符串male或female作为参数。目前,我有以下DataFrame:
Marital Gender
0 Single Female
1 Married Male
2 Married Male
3 Single Male
4 Married Female
我尝试了以下方法:
df.loc[df.Gender == 'Male', 'FirstName'] = names.get_first_name(gender = 'male')
df.loc[df.Gender == 'Female', 'FirstName'] = names.get_first_name(gender = 'female')
但是我得到的只是两个名字:
Marital Gender FirstName
0 Single Female Kathleen
1 Married Male David
2 Married Male David
3 Single Male David
4 Married Female Kathleen
是否有一种方法可以针对每一行分别调用此函数,所以并非所有的男性/女性都具有相同的确切名称?
答案 0 :(得分:2)
您需要apply
df['Firstname']=df['Gender'].str.lower().apply(names.get_first_name)
答案 1 :(得分:1)
您可以使用列表理解:
df['Firstname']= [names.get_first_name(gender) for gender in df['Gender'].str.lower()]
听说有一个黑客程序,它会按性别(及其概率)读取所有名称,然后随机采样。
import names
def get_names(gender):
if not isinstance(gender, (str, unicode)) or gender.lower() not in ('male', 'female'):
raise ValueError('Invalid gender')
with open(names.FILES['first:{}'.format(gender.lower())], 'rb') as fin:
first_names = []
probs = []
for line in fin:
first_name, prob, dummy, dummy = line.strip().split()
first_names.append(first_name)
probs.append(float(prob) / 100)
return pd.DataFrame({'first_name': first_names, 'probability': probs})
def get_random_first_names(n, first_names_by_gender):
first_names = (
first_names_by_gender
.sample(n, replace=True, weights='probability')
.loc[:, 'first_name']
.tolist()
)
return first_names
first_names = {gender: get_names(gender) for gender in ('Male', 'Female')}
>>> get_random_first_names(3, first_names['Male'])
['RICHARD', 'EDWARD', 'HOMER']
>>> get_random_first_names(4, first_names['Female'])
['JANICE', 'CAROLINE', 'DOROTHY', 'DIANE']
答案 2 :(得分:0)
如果速度很重要,请使用map
list(map(names.get_first_name,df.Gender))
Out[51]: ['Harriett', 'Parker', 'Alfred', 'Debbie', 'Stanley']
#df['FN']=list(map(names.get_first_name,df.Gender))