英文:
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'])
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'] )
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论