繁体   English   中英

pandas isin 使用多个列值

[英]pandas isin using multiple column values

如果行包含我指定的列的某些值,我想为我的 pandas dataframe 中的每一行分配True/False值。 例如,假设我有以下 dataframe:

d = {
    "col1": ["alpha", "beta", "alpha", "gamma", "alpha"],
    "col2": [1, 2, 2, 3, 1],
    "col3": ["a", "a", "b", "c", "d"],
}
df = pd.DataFrame(d)
df

    col1  col2 col3
0  alpha     1    a
1   beta     2    a
2  alpha     2    b
3  gamma     3    c
4  alpha     1    d

我知道如果我想使用单个列的值创建行掩码,我可以使用 pandas 的isin 例如,如果我想要col1中包含alpha的所有行,我可以执行以下操作: df['col1'].isin(["alpha"])

0     True
1    False
2    False
3    False
4     True

我如何获得类似的行为但有多个列? 如果我想将所有在col1中具有alpha且在col2中具有1的行设置为True而其他所有行都设置为False怎么办?

我想要一个 function 接受一个 dataframe 和一个字典作为输入。 字典将具有与列名和值相对应的键作为我想要的值列表。 function 返回一个 pandas 系列布尔值,如果 dataframe 中的对应行包含字典中的值,则每一行为True ,否则为False 例如:

def multi_column_isin(df, d):
    <implementation>
    s = pandas Series where each row is True if it has values in d else False
    return s

s = multi_column_isin(df, {"col1": ["gamma", "alpha"], "col2": [1, 3]})
s

0     True
1    False
2    False
3     True
4     True

您可以编写 function 脚本来执行此操作:

def multi_column_isin(df, d):
    # get rid of the index to avoid index alignment
    booleans = [df[col].isin(arr).array for col, arr in d.items()]
    return np.logical_and.reduce(booleans)

multi_column_isin(df, {"col1": ["gamma", "alpha"], "col2": [1, 3]})
array([ True, False, False,  True,  True])


# alternative route with pipe
 df.pipe(multi_column_isin, {"col1": ["gamma", "alpha"], "col2": [1, 3]})
array([ True, False, False,  True,  True])

一种更简单的方法是将字典传递给isin - 有时,这可能会导致不正确/不需要的 output,具体取决于索引 alignment:

(df
.drop(columns='col3')
.isin({"col1": ["gamma", "alpha"], "col2": [1, 3]})
.all(1)
)

0     True
1    False
2    False
3     True
4     True
dtype: bool

IIUC:

(df.col1 == 'alpha') & (df.col2 == 1)

应该让你到那里。

暂无
暂无

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

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