【问题标题】:Question in for using numpy "where" function使用 numpy “where”函数的问题
【发布时间】:2019-03-08 04:21:05
【问题描述】:

所以我正在尝试学习 python 和一些统计数据。在有关 F 检验的一个示例代码中,出现了这一点。

np.random.seed(12)

# Generate random data

voter_race = np.random.choice(a= races, p = [0.05, 0.15 ,0.25, 0.05, 0.5], size=1000)



# Use a different distribution for white ages

white_ages = stats.poisson.rvs(loc=18, mu=32, size=1000)

voter_age = stats.poisson.rvs(loc=18, mu=30, size=1000)

voter_age = np.where(voter_race=="white", white_ages, voter_age)


# Group age data by race

voter_frame = pd.DataFrame({"race":voter_race,"age":voter_age})

groups = voter_frame.groupby("race").groups


# Extract individual groups

asian = voter_age[groups["asian"]]

black = voter_age[groups["black"]]

hispanic = voter_age[groups["hispanic"]]

other = voter_age[groups["other"]]

white = voter_age[groups["white"]]


# Perform the ANOVA

stats.f_oneway(asian, black, hispanic, other, white)

在加粗的代码中,为什么voter_race出现了两次,为什么white_ages也在np.where代码中?

【问题讨论】:

    标签: python numpy where


    【解决方案1】:

    np.where 返回 x 或 y,(第二个或第三个参数)取决于第一个参数条件是否为真。如果条件为真,则返回 x,否则返回 y。那个函数上的documentation 挺好的。

    所以这里的 np.where 语句将返回 white_ages 如果 voter_race 是 "white" 否则它会返回 voter_age。

    您的代码也没有显示为粗体,仅供参考。

    【讨论】:

    • 我的错。我首先在reddit上发布了这个,我将文本加粗,但因为没有得到回复,我将它复制到这里,因此加粗的代码消失了。不过还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2017-04-05
    • 2019-03-16
    • 2013-04-26
    • 2010-11-26
    • 2019-10-02
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多