Nirali Khoda
Nirali Khoda

Reputation: 1691

how to slice a pandas data frame with for loop in another list?

I have a dataframe like this but Its not necessary that there are just 3 sites always:

data = [[501620, 501441,501549], [501832, 501441,501549], [528595, 501662,501549],[501905,501441,501956],[501913,501441,501549]]
df = pd.DataFrame(data, columns = ["site_0", "site_1","site_2"])

I want to slice the dataframe which can take condition dynemically from li(list) element and random combination. I have tried below code which is a static one:

li = [1,2]
random_com = (501620, 501441,501549)
df_ = df[(df["site_"+str(li[0])] == random_com[li[0]]) & \
            (df["site_"+str(li[1])] == random_com[li[1]])]

How can I make the above code dynemic ?

I have tried this but It is giving me two different dataframe but I need one dataframe with both condition (AND).

 [df[(df["site_"+str(j)] == random_com[j])] for j in li]

Upvotes: 0

Views: 492

Answers (2)

Ynjxsjmh
Ynjxsjmh

Reputation: 30050

If you prefer one-liner, I think you could use reduce()

df_ = df[reduce(lambda x, y: x & y, [(df["site_"+str(j)] == random_com[j]) for j in li])]

Upvotes: 1

DeGo
DeGo

Reputation: 791

You can do an iteration over the conditions and create an & of all the conditions.

li = [1,2]
main_mask = True
for i in li:
    main_mask = main_mask & (df["site_"+str(i)] == random_com[i])
df_ = df[main_mask]

Upvotes: 2

Related Questions