[Python] Splitting numpy arrays based on categorical variable

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to split up the ages and weights based on the categorical variable "obese" and then plot the two sets with different colors. I think I might be doing the list comprehension wrong. When I plot I only see one color and all data points.

    import numpy as np
    import matplotlib.pyplot as plt
    ages = np.array([20, 22, 23, 25, 27])
    weights = np.array([140, 144, 150, 156, 160])
    obese = np.array([0, 0, 0, 1, 1])

    ages_normal = [ages for i in range(0, len(obese)) if obese == 0]
    weights_normal = [weights for i in range(0, len(obese)) if obese == 0]

    ages_obese = [ages for i in range(0, len(obese)) if obese == 1]
    weights_obese = [weights for i in range(0, len(obese)) if obese == 1]

    plt.scatter(ages_normal, weights_normal, color = "b")
    plt.scatter(ages_obese, weights_obese, color = "r")
    plt.show()

    Continue reading...

Compartilhe esta Página