简体   繁体   中英

How to select rows where items of two columns match with items of two lists (same index), using Pandas?

The question is the same as the one answered here but extended to two conditionals. This may be tricky because the Pandas method 'isin' cannot be used as that would result in looking at combinations of items in my two lists, while what I want is to compare (and select) the dataframe items corresponding to list items of identical index (eg pairs of xn,yn from lists of X=[x1,x2,...xn], Y=[y1,y2,..yn]). The lists can be converted to a dataframe if needed.

Is there a way to generalize this to multiple (more than two) conditionals in Pandas?

You could do:

df[df['col1'].isin(list1) & df['col2'].isin(list2)]

This will return the rows of df where the value of col1 exists in list1 and the value of col2 exists in list2 .

& is the bitwise AND operator, and will return True on the indices where both the operands are True.

What worked in the end is something like this:

df4=pd.DataFrame(columns=df.keys())
for i, lat in enumerate(list1): 
    lon = list2[i]
    df2 = df[df["Lat"]==lat]
    df3 = df2[df2["Lon"]==lon]
    df4 = pd.concat([df4, df3],ignore_index=True)

Maybe not the most efficient way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM