Let's say that I have a pandas DataFrame:
import pandas as pd
df = pd.DataFrame({'id': [0, 2, 1], 'name': ['Sheldon', 'Howards', 'Leonard'], 'points': [10, 5, 20]})
I wanted to search for a row with the values {'id': 2, 'name': 'Howards', 'points': 5}
inside this DataFrame. How can I search it to receive the index from it, if it exists?
Here comes my problem. I have a method that receives a dict with unknown keys and a DataFrame with unknown columns too. I need to search inside this DataFrame to discover if I have the searched row inside than...
I found this answer that says about a method named iterrows. Is this the best way to find the row? Code:
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index()
search = {'c1': 12, 'c2': 120}
index = -1
for idx, row in df.iterrows():
if row == search:
index = idx
If not, what is the best way?
With np.logical_and
on filter clauses:
df.index[np.logical_and(*[df[k].eq(v) for k, v in search_d.items()])]
Index([1], dtype='int64')