[Python] boolean indexing using .isin simply returns the series it is indexing, not the values...

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    here's the dataset and the problem I'm working with

    import numpy as np
    import pandas as pd

    couples = pd.DataFrame({
    'man': [
    ['fishing', 'biking', 'reading'],
    ['hunting', 'mudding', 'fishing'],
    ['reading', 'movies', 'running'],
    ['running', 'reading', 'biking', 'mudding'],
    ['movies', 'reading', 'yodeling']
    ],
    'woman': [
    ['biking', 'reading', 'movies'],
    ['fishing', 'drinking'],
    ['knitting', 'reading'],
    ['running', 'biking', 'fishing', 'movies'],
    ['movies']
    ]
    })

    print(couples)
    # man woman
    # 0 [fishing, biking, reading] [biking, reading, movies]
    # 1 [hunting, mudding, fishing] [fishing, drinking]
    # 2 [reading, movies, running] [knitting, reading]
    # 3 [running, reading, biking, mudding] [running, biking, fishing, movies]
    # 4 [movies, reading, yodeling] [movies]


    For each couple, determine what hobbies each man has that his wife doesn’t and what hobbies each woman has that her husband doesn’t.

    I tried solving it the way shown below: couples['hobbies than man has that woman doesnt'] = couples['man'][~couples['man'].isin(couples['woman'])]

    but instead of returning fishing in the 1st line, hunting and mudding in the 2nd and so on, it simply returns the first column:

    man woman hobbies than man has that woman doesnt
    0 [fishing, biking, reading] [biking, reading, movies] [fishing, biking, reading]
    1 [hunting, mudding, fishing] [fishing, drinking] [hunting, mudding, fishing]
    2 [reading, movies, running] [knitting, reading] [reading, movies, running]
    3 [running, reading, biking, mudding] [running, biking, fishing, movies] [running, reading, biking, mudding]
    4 [movies, reading, yodeling] [movies] [movies, reading, yodeling]


    I've also tried converting both columns to str type before creating the third column but the result is the same. why does that happen and how do I fix it?

    Continue reading...

Compartilhe esta Página