如何使用最少的代码创建过滤的DataFrame

时间:2016-08-31 04:35:51

标签: python pandas indexing dataframe conditional-statements

有四辆车:bmwgeovwporsche

import pandas as pd
df = pd.DataFrame({
    'car':      ['bmw','geo','vw','porsche'],
    'warranty': ['yes','yes','yes','no'], 
    'dvd':      ['yes','yes','no','yes'], 
    'sunroof':  ['yes','no','no','no']})

enter image description here

我想创建一个过滤的DataFrame,它只列出那些具有所有三种功能的汽车:DVD播放器,天窗和保修(我们知道这里的宝马所有功能都设置为'是')。

我可以在以下时间用一栏完成:

cars_with_warranty = df['car'][df['warranty']=='yes']
print(cars_with_warranty)

enter image description here

然后我需要为dvd和天窗列进行类似的列计算:

cars_with_dvd = df['car'][df['dvd']=='yes']
cars_with_sunroof = df['car'][df['sunroof']=='yes']

我想知道是否有一种聪明的方法来创建过滤的DataFrame

以后编辑:

发布的解决方案效果很好。但结果cars_with_all_three是一个简单的列表变量。我们需要DataFrame对象,只有一个'bmw'汽车作为唯一的行和所有三列:dvd,天窗和保修(所有三个值都设置为'是')。

cars_with_all_three = []
for ind, car in enumerate(df['car']):
    if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes':
        cars_with_all_three.append(car)

3 个答案:

答案 0 :(得分:4)

您可以使用boolean indexing

print ((df.dvd == 'yes') & (df.sunroof == 'yes') & (df.warranty == 'yes'))
0     True
1    False
2    False
3    False
dtype: bool

print (df[(df.dvd == 'yes') & (df.sunroof == 'yes') & (df.warranty == 'yes')])
   car  dvd sunroof warranty
0  bmw  yes     yes      yes

#if need filter only column 'car' 
print (df.ix[(df.dvd == 'yes')&(df.sunroof == 'yes')&(df.warranty == 'yes'), 'car'])
0    bmw
Name: car, dtype: object

另一个解决方案,检查列中的所有值是否为yes,然后all检查所有值是否为True

print ((df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1))
0     True
1    False
2    False
3    False
dtype: bool

print (df[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)])
   car  dvd sunroof warranty
0  bmw  yes     yes      yes

print (df.ix[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1), 'car'])
0    bmw
Name: car, dtype: object

使用最少代码的解决方案,如果DataFrame只有4列,例如sample:

print (df[(df.set_index('car') == 'yes').all(1).values])
   car  dvd sunroof warranty
0  bmw  yes     yes      yes

<强>计时

In [44]: %timeit ([car for ind, car in enumerate(df['car']) if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes'])
10 loops, best of 3: 120 ms per loop

In [45]: %timeit (df[(df.dvd == 'yes')&(df.sunroof == 'yes')&(df.warranty == 'yes')])
The slowest run took 4.39 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 2.09 ms per loop

In [46]: %timeit (df[(df[[ u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)])
1000 loops, best of 3: 1.53 ms per loop

In [47]: %timeit (df[(df.ix[:, [u'dvd', u'sunroof', u'warranty']] == "yes").all(axis=1)])
The slowest run took 4.46 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.51 ms per loop

In [48]: %timeit (df[(df.set_index('car') == 'yes').all(1).values])
1000 loops, best of 3: 1.64 ms per loop

In [49]: %timeit (mer(df))
The slowest run took 4.17 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.85 ms per loop

时间安排的代码

df = pd.DataFrame({
    'car':      ['bmw','geo','vw','porsche'],
    'warranty': ['yes','yes','yes','no'], 
    'dvd':      ['yes','yes','no','yes'], 
    'sunroof':  ['yes','no','no','no']})

print (df)
df = pd.concat([df]*1000).reset_index(drop=True)

def mer(df):
    df = df.set_index('car')
    return df[df[[ u'dvd', u'sunroof', u'warranty']] == "yes"].dropna().reset_index()

答案 1 :(得分:4)

试试这个:

df = df.set_index('car')
df[df[[ u'dvd', u'sunroof', u'warranty']] == "yes"].dropna().reset_index()

 df
   car  dvd sunroof warranty
0  bmw  yes     yes      yes


df = df.set_index('car')
df[df[[ u'dvd', u'sunroof', u'warranty']]== "yes"].dropna().index.values

['bmw']   

答案 2 :(得分:3)

您可以使用简单loopenumerate

cars_with_all_three = []
for ind, car in enumerate(df['car']):
    if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes':
        cars_with_all_three.append(car)

如果您执行print(cars_with_all_three),则会获得['bmw']

或者,如果你想变得非常聪明并且使用单行,你可以这样做:

[car for ind, car in enumerate(df['car']) if df['dvd'][ind] == df['warranty'][ind] == df['sunroof'][ind] == 'yes']

希望有所帮助