2017-05-29 62 views
1

我想选择传递字典或理解列表的数据框中的行。通过传递参数或理解列表来选择数据帧python熊猫

我有一个数百万行的数据框,我想创建一个函数来只选择这个数据框的一部分对应于一个参数列表。为了复杂性,我必须传递数据框和列表,但是这个列表可以包含NaN值和'0'。所以我必须删除这个条目来选择正确的行。

的参赛名单:

b = ['MUSTANG', 'Coupé', '0', np.nan, np.nan] 

    AGE KM  Brand Model   Liter  Bodycar Power 
0 2.0 10000.0 FORD MUSTANG   5.0  Coupé 421 
1 2.0 10000.0 FORD MUSTANG   5.0  Coupé 421 
2 5.0 10400.0 FORD MUSTANG   5.0  Coupé 421 
3 5.0 10400.0 FORD MUSTANG   5.0  Coupé 421 
4 16.0 20700.0 FORD MUSTANG   3.7  Coupé 317 
5 7.0 23300.0 FORD MUSTANG   3.7     317 
6 7.0 23300.0 FORD MUSTANG   2.3  Coupé 301 
7 7.0 23300.0 FORD MUSTANG   5.0     421 
... 

I started a function to remove the part of the list useless and try to select the proper rows but failed... 

    def func_mcclbp_incomp(df, mcclbp): 
    ind = [] 

    mcclbp = [i if type(i) == str else '0' for i in mcclbp] 
    ind = [i for i, x in enumerate(mcclbp) if x=='0'] 

    head = ['Brand','Model','Bodycar','Liter', 'Power'] 
    mmcclbp = {head[0]:mcclbp[0], head[1]:mcclbp[1], head[2]:mcclbp[2], \ 
      head[3]:mcclbp[3], head[4]:mcclbp[4]} 
    for i in ind: 
     del mmcclbp[head[i]] 
    df = df[df[head[i]==mccblp[i]] for i in mmcclbp.key()] 
    return df 

我尝试了修真名单,但大熊猫给我一个错误:

File "<ipython-input-235-6f78e45f59d4>", line 1 
df = df[df[head[i].isin(mccblp[i]) for i in mmcclbp.keys()]] 
            ^
SyntaxError: invalid syntax 

当我试图传递一个字典我有一个KeyError异常。

如果我采用B所需的输出是:

 AGE KM  Brand Model   Liter  Bodycar Power 
0 2.0 10000.0 FORD MUSTANG   5.0  Coupé 421 
1 2.0 10000.0 FORD MUSTANG   5.0  Coupé 421 
2 5.0 10400.0 FORD MUSTANG   5.0  Coupé 421 
3 5.0 10400.0 FORD MUSTANG   5.0  Coupé 421 
4 16.0 20700.0 FORD MUSTANG   3.7  Coupé 317 
6 7.0 23300.0 FORD MUSTANG   2.3  Coupé 301 

如果我改变b键像另一个值:

b = ['FORD', 'MUSTANG', 'Coupé', '3.7', '317'] 

结果将是:

 AGE KM  Brand Model   Liter  Bodycar Power 
4 16.0 20700.0 FORD MUSTANG   3.7  Coupé 317 

有人知道我如何可以自动选择列出相应的行?

感谢您的回答,

Chris。

+0

才能添加所需的从'B = [“野马”,'轿跑车的输出, '0',np.nan,np.nan]'和你的样本数据? – jezrael

+0

是的,对不起,我忘了写输入...编辑显示你我需要做什么。 –

+0

你能解释更多的第一个输出 - 为什么得到数据,如果有'0'或'nan's? – jezrael

回答

1

您可以使用dict进行筛选,使用DataFrame.all检查所有True掩膜和筛选器的每个值的值为boolean indexing
还需要转换的astypeDataFramestring一切都值,因为dict的所有valuesstring太:

d = {'Brand':'FORD', 'Model':'MUSTANG', 'Bodycar':'Coupé', 'Liter':'3.7', 'Power':'317'} 

print (df.astype(str)[list(d)] == pd.Series(d)) 
    Bodycar Brand Liter Model Power 
0  True True False True False 
1  True True False True False 
2  True True False True False 
3  True True False True False 
4  True True True True True 
6  True True False True False 

mask = (df.astype(str)[list(d)] == pd.Series(d)).all(axis=1) 
print (mask) 
0 False 
1 False 
2 False 
3 False 
4  True 
6 False 
dtype: bool 

df1 = df[mask] 
print (df1) 
    AGE  KM Brand Model Liter Bodycar Power 
4 16.0 20700.0 FORD MUSTANG 3.7 Coupé 317 
+0

非常感谢这个答案!这工作得很好!!!!! –

+0

再次感谢!你也是 :) –