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
print (df.ix[(df.dvd == 'yes')&(df.sunroof == 'yes')&(df.warranty == 'yes'), 'car'])
0 bmw
Name: car, dtype: object
, yes, , True all:
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()