python – 如何通过多列过滤pandas数据帧
发布时间:2020-12-20 10:32:07 所属栏目:Python 来源:网络整理
导读:要按单列过滤数据框(df),如果我们考虑男性和女性的数据,我们可能会: males = df[df[Gender]=='Male'] 问题1 – 但如果数据跨越多年并且我只想看2014年的男性怎么办? 在其他语言中,我可能会这样做: if A = "Male" and if B = "2014" then (除了我想这样做
要按单列过滤数据框(df),如果我们考虑男性和女性的数据,我们可能会:
males = df[df[Gender]=='Male'] 问题1 – 但如果数据跨越多年并且我只想看2014年的男性怎么办? 在其他语言中,我可能会这样做: if A = "Male" and if B = "2014" then (除了我想这样做并在新的dataframe对象中获取原始数据帧的子集) 问题2.如何在循环中执行此操作,并为每个独特的年份和性别集创建数据框对象(即:2013年男性,2013年女性,2014年男性和2014年女性的df for y in year: for g in gender: df = ..... 解决方法
使用&运算符,不要忘记用()包装子语句:
males = df[(df[Gender]=='Male') & (df[Year]==2014)] 使用for循环将数据帧存储在dict中: from collections import defaultdict dic={} for g in ['male','female']: dic[g]=defaultdict(dict) for y in [2013,2014]: dic[g][y]=df[(df[Gender]==g) & (df[Year]==y)] #store the DataFrames to a dict of dict 编辑: getDF的演示: def getDF(dic,gender,year): return dic[gender][year] print genDF(dic,'male',2014) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |