【发布时间】:2020-02-13 10:33:01
【问题描述】:
我有一个包含 3 列的数据框:
[输入]:
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 的“Circle”id 计数为 9168,0 为 28152。我需要的计算:(9168)/(9168+28152)。我用这段代码实现了这个计算。
[输入]:
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 目标行时,我会收到 IndexError。在这种情况下,“梯形”缺少 0 目标行。因此,如果几何形状的两个 0,1 目标都存在,我喜欢上面提到的计算。如果缺少 1 个目标,我希望结果等于 0,如果缺少 0 个目标,则结果应等于 1。例如,对于“梯形”,结果应为 1。
这是我尝试过的:
[输入]:
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]})
【问题讨论】:
-
所以你只想要那个目标 == 1?你能添加一个输出DataFrame的例子吗?
-
当您的其余数字由于公式而在 [0,1] 之间时,您希望梯形为 5000?为什么不是 1?
-
@DanielMesejo 我想要 1/(1+0) 的比率。添加了一个示例 output_df
-
@ALollz 你是对的我编辑了这个问题。如果缺少目标 0 的行,则输出应为 1。
标签: python pandas pandas-groupby apply