gpt4 book ai didi

python - 如何根据 Pandas 中的列值选择行

转载 作者:行者123 更新时间:2023-12-02 18:01:35 25 4
gpt4 key购买 nike

我创建了一个这样的数据集,

Gender    response
female yes
male yes
female yes
female no
male yes
female no
male yes
male no
female no

我喜欢按性别计算"is"的回答和“否”的回答。就像有两个女性说“不”,还有两个女性说"is"。有 3 名男性说是,1 名说不是。

我尝试使用 pandas dataframe 来实现这一点。

到目前为止,我已经尝试写下这样的查询

df.loc[df['Gender'] == 'female' & (df['response'] == 'yes')]

但是我遇到了错误。我该如何写下来?

谢谢。

最佳答案

您可以将 value_countsgroupby 方法一起使用,如下所示:

df.groupby('Gender')['response'].value_counts()

回应:

Gender  response
female no 3
yes 2
male yes 3
no 1

关于python - 如何根据 Pandas 中的列值选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74243110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com