如果一行不存在,则在Python中检查并相应地指定一个值

2024-09-22 14:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含3列的数据框:

[in]:

import pandas as pd
import numpy as np
df = pd.DataFrame([['Circle', 'Circle', 'Polygon', 'Polygon',"Trapezoid"], 
                   [0, 1, 0, 1,1], [28152, 9168, 24741, 11402,5000]], 
                   ['nom_1', 'target', 'id']).T 

[输出]:

       nom_1 target     id
0     Circle      0  28152
1     Circle      1   9168
2    Polygon      0  24741
3    Polygon      1  11402
4  Trapezoid      1   5000

理论上,每个几何形状在目标列中的值应为0或1。Id表示计数。我需要id列中每个几何图形的1/(1+0)比率。你知道吗

例如,目标1的“圆”id计数为9168,目标0的“圆”id计数为28152。我需要的计算:(9168)/(9168+28152)。我用这段代码实现了这个计算。你知道吗

[in]:

ColumnTarget = df[["id","nom_1","target"]]
ColumnGrouped = ColumnTarget.groupby(["nom_1","target"]).count()["id"].reset_index()
ColumnCalculation = ColumnGrouped.groupby("nom_1").apply(lambda row: (row[row.target ==1]["id"].iloc[0]) / (row[row.target ==0]["id"].iloc[0] + row[row.target ==1]["id"].iloc[0]))

[输出]:

IndexError: single positional indexer is out-of-bounds

但是当一个几何形状没有1或0目标行时,我得到一个索引器。在本例中,“梯形”缺少0目标行。因此,如果两个0,1目标都存在于几何形状中,我喜欢上面的计算。如果缺少1个目标,我希望结果等于0,如果缺少0个目标,结果应该等于1。例如,对于“梯形”,结果应为1。你知道吗

以下是我尝试的:

[in]:

ColumnTarget = df[["id","nom_1","target"]]
ColumnGrouped = ColumnTarget.groupby(["nom_1","target"]).count()["id"].reset_index()
ColumnCalculation = ColumnGrouped.groupby("nom_1").apply(lambda row: 0 if row[row.target ==1].all() is False else (1 if row[row.target ==0].all() is False else ((row[row.target ==1]["id"].iloc[0]) / (row[row.target ==0]["id"].iloc[0] + row[row.target ==1]["id"].iloc[0]))))

[输出]:

IndexError: single positional indexer is out-of-bounds

output_df = pd.DataFrame({"nom_1":["Circle","Polygon","Trapezoid"],"result": [0.24565916398713827,0.3154691088177517,1]})

Tags: inidtarget目标dfisnomrow
2条回答

使用transformdiv

df['id'].div(df.groupby('nom_1').id.transform('sum'), axis=0)

       nom_1 target     id     ratio
0     Circle      0  28152  0.754341
1     Circle      1   9168  0.245659
2    Polygon      0  24741  0.684531
3    Polygon      1  11402  0.315469
4  Trapezoid      1   5000         1

很明显,您可以编辑这个df来可视化那些带有target == 1的行

df[df.target == 1]

       nom_1 target     id     ratio
1     Circle      1   9168  0.245659
3    Polygon      1  11402  0.315469
4  Trapezoid      1   5000         1

使用index对齐计算(我添加了一个shape missing Target==1)。这假设您在['nom_id', 'target']上没有任何重复的内容:

df = pd.DataFrame([['Circle', 'Circle', 'Polygon', 'Polygon',"Trapezoid", 'Octagon'], 
                   [0, 1, 0, 1, 1, 0], [28152, 9168, 24741, 11402,5000, 6000]], 
                   ['nom_1', 'target', 'id']).T 

df = df.set_index('nom_1')
u = df.loc[df.target.eq(1), 'id']
v = df.loc[df.target.eq(0), 'id']

                                    # - 0 When Target == 1 is missing
                                    # |
s = u.divide(u.add(v, fill_value=0)).fillna(0)
#nom_1
#Circle       0.245659
#Octagon      0.000000
#Polygon      0.315469
#Trapezoid    1.000000
#Name: id, dtype: float64

相关问题 更多 >