根据标准(性别)拆分清单

时间:2014-11-08 16:23:08

标签: python list function pandas append

我是python的初学者,只是学习如何编写函数。我有一个权重和性别列表,我试图将其拆分为根据性别标准创建两个新列表。使用for循环,到目前为止我已经成功了:

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)

如何将此for循环修改为变量= m / f(性别)的函数?

1 个答案:

答案 0 :(得分: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()