我有一个包含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]})
使用
transform
和div
很明显,您可以编辑这个
df
来可视化那些带有target == 1
的行使用
index
对齐计算(我添加了一个shape missing Target==1)。这假设您在['nom_id', 'target']
上没有任何重复的内容:相关问题 更多 >
编程相关推荐