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 inside this DataFrame a row with the values {'id': 2, 'name': 'Howards', 'points': 5}, How can I search it to receive the index from than, if exists?
And now come my problem. I have a method that receive a dict with unknow keys and a DataFrame with unknow columns too. I need to search inside this DataFrame to discover if have the searched row inside than…
I finded this answer that says about a method named iterrows. It’s the better 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 the better way?
>Solution :
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')