mardi 10 novembre 2020

Replacing variables in csv with a randomly generated variable

I am wanting to replace variables in a CSV file with a randomly generated variable for each of the variables.

For instance, changing 'not available' to either 'male' or 'female'

Sample:

Number    Sex
0         Female
1         Male
2         Not Available
3         Male
4         Not Available

To:

Number    Sex
0         Female
1         Male
2         Female
3         Male
4         Male

The code that I have right now is:

import pandas as pd
import random

def RandomSex():
    return random.choice(['Male','Female'])



df = pd.read_csv(r'data.csv')
df2 = df.loc[: , 'Sex']
print(df2)
df.loc[(df.Sex == 'Not Available'),'Gender'] = RandomSex()
print(df2)

But this is changing all of the 'Not Available' to either all 'Male' or all 'Female'

I appreciate the help!




Aucun commentaire:

Enregistrer un commentaire