我想找出列中具有特定值的行的百分比.并找到其他两列的每个组合的百分比.

以下是df示例:

data =[['North Shields','UK','Y'],['North Shields','Foreign','N']]
df = pd.DataFrame(data, columns = ['Port','Type','Shellfish Licence licence (Y/N)']
df 

我try 了以下方法,但出现了一个关键错误,可能是因为我无法以这种方式对两列进行Groupby.

port_shel_df = landing_fish_merge['Shellfish Licence licence 
(Y/N)'].eq('Y').groupby(port_merge_lic_df['Port','Type]).mean().reset_index(name='Shellfish 
license 
percentage')
port_shel_df = port_shel_df.set_index('Port')
port_shel_df[:1]

推荐答案

创建助手列并按其聚合:

df = (landing_fish_merge.assign(new= landing_fish_merge['Shellfish Licence licence (Y/N)'].eq('Y'))
                        .groupby(['Port','Type'])['new'].mean()
                        .reset_index(name='Shellfish license percentage'))

Python相关问答推荐

如何将Pydantic URL验证限制为特定主机或网站

预期LP_c_Short实例而不是_ctyles.PyCStructType

如何知道标志是否由用户传递或具有默认值?

使用argsorted索引子集索引数组

遵循轮廓中对象方向的计算线

按照行主要蛇扫描顺序对点列表进行排序

如何使用矩阵在sklearn中同时对每个列执行matthews_corrcoef?

Polars:使用列值引用when / then表达中的其他列

将HLS纳入媒体包

如何根据日期和时间将状态更新为已过期或活动?

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

try 在树叶 map 上应用覆盖磁贴

如何让程序打印新段落上的每一行?

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

如何在python polars中停止otherate(),当使用when()表达式时?

我如何根据前一个连续数字改变一串数字?

将输入聚合到统一词典中

给定高度约束的旋转角解析求解

dask无groupby(ddf. agg([min,max])?''''

Python—转换日期:价目表到新行