When selecting rows whose column value column_name equals a scalar, some_value, we use ==:
df.loc[df['column_name'] == some_value]
or use .query()
df.query('column_name == some_value')
In a concrete example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Col1': 'what are men to rocks and mountains'.split(),
'Col2': 'the curves of your lips rewrite history.'.split(),
'Col3': np.arange(7),
'Col4': np.arange(7) * 8})
print(df)
Col1 Col2 Col3 Col4
0 what the 0 0
1 are curves 1 8
2 men of 2 16
3 to your 3 24
4 rocks lips 4 32
5 and rewrite 5 40
6 mountains history 6 48
A query could be
rocks_row = df.loc[df['Col1'] == "rocks"]
which outputs
print(rocks_row)
Col1 Col2 Col3 Col4
4 rocks lips 4 32
I would like to pass through a list of values to query against a dataframe, which outputs a list of "correct queries".
The queries to execute would be in a list, e.g.
list_match = ['men', 'curves', 'history']
which would output all rows which meet this condition, i.e.
matches = pd.concat([df1, df2, df3])
where
df1 = df.loc[df['Col1'] == "men"]
df2 = df.loc[df['Col1'] == "curves"]
df3 = df.loc[df['Col1'] == "history"]
My idea would be to create a function that takes in a
output = []
def find_queries(dataframe, column, value, output):
for scalar in value:
query = dataframe.loc[dataframe[column] == scalar]]
output.append(query) # append all query results to a list
return pd.concat(output) # return concatenated list of dataframes
However, this appears to be exceptionally slow, and doesn't actually take advantage of the pandas data structure. What is the "standard" way to pass through a list of queries through a pandas dataframe?
EDIT: How does this translate into "more complex" queries in pandas? e.g. where with an HDF5 document?
df.to_hdf('test.h5','df',mode='w',format='table',data_columns=['A','B'])
pd.read_hdf('test.h5','df')
pd.read_hdf('test.h5','df',where='A=["foo","bar"] & B=1')