简体   繁体   中英

Create Names column in Pandas DataFrame

I am using the Python Package names to generate some first names for QA testing.

The names package contains the function names.get_first_name(gender) which allows either the string male or female as the parameter. Currently I have the following DataFrame:

    Marital Gender
0   Single  Female
1   Married Male
2   Married Male
3   Single  Male
4   Married Female

I have tried the following:

df.loc[df.Gender == 'Male', 'FirstName'] = names.get_first_name(gender = 'male')
df.loc[df.Gender == 'Female', 'FirstName'] = names.get_first_name(gender = 'female')

But all I get in return is the are just two names:

    Marital Gender  FirstName
0   Single  Female  Kathleen
1   Married Male    David
2   Married Male    David
3   Single  Male    David
4   Married Female  Kathleen

Is there a way to call this function separately for each row so not all males/females have the same exact name?

你需要申请

 df['Firstname']=df['Gender'].str.lower().apply(names.get_first_name)

You can use a list comprehension:

df['Firstname']= [names.get_first_name(gender) for gender in df['Gender'].str.lower()] 

And hear is a hack that reads all of the names by gender (together with their probabilities), and then randomly samples.

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']

If the speed is matter using 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM