簡體   English   中英

與列表類型列的逐行比較

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

假設我有以下代碼

import pandas as pd

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

並產生 Pandas dataframe:

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

有沒有辦法在不使用 for 循環或itertools package 的情況下將整數類型值與同一行中的相應列表進行比較? 基本上我想要的是一個掩碼來過濾列表中包含 integer 的行。 到目前為止,我無法獲得像isin這樣的方法(需要列表已經作為參數,這需要逐行索引)或一般比較工作(將列表與整數進行比較)。 幫助表示贊賞!

一種使用pandas.DataFrame.apply方法:

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

Output:

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

嘗試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