Python: 我尝试使用groupby的value_count时出现KeyError: ‘Yes’错误。

huangapple go评论75阅读模式
英文:

Python: I get a KeyError: 'Yes' when I try to use value_count with groupby

问题

df = pd.DataFrame({'deliveryzipcode':['75202', '75202', '75202', '60660', '60660', '60660', '60660'],
                   'orderreturned': ['Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No']})
df
print(df.groupby('deliveryzipcode')['orderreturned'].value_counts()['Yes'])

Python: 我尝试使用groupby的value_count时出现KeyError: ‘Yes’错误。

searched for Python Key Error to see what others have encountered and did to resolve the problem.

英文:
df = pd.DataFrame({'deliveryzipcode':['75202', '75202', '75202', '60660', '60660', '60660', '60660'],
                        'orderreturned': ['Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No']})
df
print(df.groupby('deliveryzipcode')['orderreturned'].value_counts()['Yes'] )

Python: 我尝试使用groupby的value_count时出现KeyError: ‘Yes’错误。

searched for Python Key Error to see what others have encountered adn did to erolve the problem.

答案1

得分: 0

从您的DataFrame中,我们可以使用groupby,将as_index参数设置为False,并在df上过滤出Yes值,以获得如下所示的干净DataFrame:

df[df['orderreturned']=='Yes'].groupby('deliveryzipcode', as_index=False)['orderreturned'].value_counts()

输出:

 	deliveryzipcode 	orderreturned 	count
0 	60660           	Yes          	1
1 	75202           	Yes          	2
英文:

From your DataFrame, we can use the groupby with the as_index parameter set to False, and filter the df on the Yes value to get a clean DataFrame like so :

df[df['orderreturned']=='Yes'].groupby('deliveryzipcode', as_index=False)['orderreturned'].value_counts()

Output :

 	deliveryzipcode 	orderreturned 	count
0 	60660           	Yes          	1
1 	75202           	Yes          	2

答案2

得分: 0

你可以使用 Dataframe.xs 通过索引选择特定的行:

grouped_df = df.groupby("deliveryzipcode")["orderreturned"].value_counts()
print(grouped_df.xs("Yes", level=1))

打印:

60660    1
75202    2
Name: count, dtype: int64
英文:

You can use Dataframe.xs to select only certain rows by index:

grouped_df = df.groupby("deliveryzipcode")["orderreturned"].value_counts()
print(grouped_df.xs("Yes", level=1))

Prints:

60660    1
75202    2
Name: count, dtype: int64

huangapple
  • 本文由 发表于 2023年8月4日 05:24:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定