简体   繁体   English

与列表类型列的逐行比较

[英]Row-wise comparison against a list-type column

let's assume I have the following code假设我有以下代码

import pandas as pd

df = pd.DataFrame({'List type':[[1, 2, 3], [4, 5, 6], [7, 8, 9]], 'Integer type':[5, 4, 1]})

and resulting Pandas dataframe:并产生 Pandas dataframe:

| List-type | Integer-type |
| --------  | -------------|
| [1, 2, 3] |      5       |
| [4, 5, 6] |      4       |
| [7, 8, 9] |      1       |

Is there a way to compare the integer-type values against the respective list in the same row without using a for loop, or the itertools package?有没有办法在不使用 for 循环或itertools package 的情况下将整数类型值与同一行中的相应列表进行比较? Basically what I want is a mask to filter for the rows where the integer is contained in the list.基本上我想要的是一个掩码来过滤列表中包含 integer 的行。 I could not get methods like isin (requires the list already as argument, which requires row-wise indexing) or general comparisons to work (compares the list against the integer) so far.到目前为止,我无法获得像isin这样的方法(需要列表已经作为参数,这需要逐行索引)或一般比较工作(将列表与整数进行比较)。 Help is appreciated!帮助表示赞赏!

One way using pandas.DataFrame.apply :一种使用pandas.DataFrame.apply方法:

df["mask"] = df.apply(lambda x: x["Int-type"] in x["List-type"], axis=1)
print(df)

Output: Output:

   List-type  Int-type   mask
0  [1, 2, 3]         5  False
1  [4, 5, 6]         4   True
2  [7, 8, 9]         1  False

Try with explode尝试explode

s = df.explode('List type')
df['new'] = s["Integer type"].eq(s["List type"]).any(level=0)
df
Out[35]: 
   List type  Integer type    new
0  [1, 2, 3]             5  False
1  [4, 5, 6]             4   True
2  [7, 8, 9]             1  False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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