0

I'm a beginner in python, just learning how to write functions. I've got a list of weights and gender, and am trying to split it to create two new lists according to the gender criteria. Using for loops, I've been successful so far:

df = pd.read_csv('brainweight.csv')
w = list(df['Weight'])
s = list(df['Sex'])

female_weight = []
male_weight = []

for sex, weight in zip (s, w):
    if sex == 'f':
        female_weight.append(weight)
    else:
        male_weight.append(weight)

How should I modify this for loop into a function where the variables = m/f (gender)?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

0
df = pd.read_csv('brainweight.csv')
w = list(df['Weight'])
s = list(df['Sex'])
def list_by_gender():
    females = []
    males = []
    for sex, weight in zip (s, w):
        if sex == 'f':
            females.append(weight)
        else:
            males.append(weight)
    return males,females

male_list,female_list=list_by_gender()
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
  • Thank you so much! Would you mind explaining the last line? I noticed that the male_list and female_list were something that wasn't defined beforehand. I wrote something very similar to your function but python just wasn't giving me the correct values... – Nack Srismith Nov 08 '14 at 17:10
  • In python you don't need **variable declarations** in the beginning like **C** and we can initialize many variables in one line like `a,b,c = 1,2,3` anywhere in the script. In the last line I am assigning `male_list` and `female_list` values directly returned from the function. It is similar to write `a,b=2,3`. – Irshad Bhat Nov 08 '14 at 17:17
  • @NackSrismith, please accept the answer if you find it helpful. – Irshad Bhat Nov 08 '14 at 17:23