python数据框中的多列过滤

时间:2019-03-28 18:30:31

标签: python dataframe filtering multiple-columns

我创建了一个熊猫数据框。我想用值9, 12, 24, 18过滤所有内容。

df:

index   no1 no2 no3 no4 no5 no6 no7 
1       9   11  12  14  18  24  30
2       9   12  13  18  19  24  31
3       9   12  13  42  20  19  24
4       10  9   13  42  18  24  12
5       13  12  13  44  18  24  30
6       2   9   12  18  24  31  44
7       10  12  14  42  18  24  30
8       10  12  14  42  18  24  31

代码:

a = df['no1'].isin([9,12,18 ,24])
b = df['no2'].isin([9,12,18,24])
c = df['no3'].isin([9,12 , 18, 24])
d = df['no4'].isin([9,12 , 18, 24])
e = df['no5'].isin([9,12,18,24])
f = df['no6'].isin([9,12 , 18, 24])
g = df['no7'].isin([9,12 , 18, 24])


df [a & b & c & d & e &  f &  g]

所需的输出:

  index   no1     no2     no3    no4     no5     no6     no7 
    1       9       11      12     14      18      24      30
    2       9       12      13     18      19      24      31
    4       10       9      13     42      18      24      12
    6       2        9      12     18      24      31      44

original data frame and expected output

2 个答案:

答案 0 :(得分:0)

尝试:

df[df.isin([9,12,18,24])]

答案 1 :(得分:0)

这应该给您确切的答案

df=pd.DataFrame({'no1':[9,9,9,10,13,2,10,10],
                 'no2':[11,12,12,9,12,9,12,12],
                 'no3':[12,13,13,13,13,12,14,14],
                 'no4':[14,18,42,42,44,18,42,42],
                 'no5':[18,19,20,18,18,24,18,18],
                 'no6':[24,24,19,24,24,31,24,24],
                 'no7':[30,31,24,12,30,44,30,31]}) # Creating the data frame
df_new=df[df.isin([9,12,18,24])]
df_new=df_new.dropna(thresh=4)
df_new=df_new.fillna(df)

结果将是:

    no1   no2   no3   no4   no5   no6   no7
0   9.0  11.0  12.0  14.0  18.0  24.0  30.0
1   9.0  12.0  13.0  18.0  19.0  24.0  31.0
3  10.0   9.0  13.0  42.0  18.0  24.0  12.0
5   2.0   9.0  12.0  18.0  24.0  31.0  44.0