假设我有一个包含一列概率的数据框。现在,我创建了一个映射函数,如果概率>阈值,则返回1,否则返回0。现在要抓住的是,我想通过将阈值作为函数的参数来指定阈值,然后将其映射到pandas数据帧上
采用以下代码示例:
def partition(x,threshold):
if x<threshold:
return 0
else:
return 1
df=pd.DataFrame({'probability':[0.2,0.8,0.4,0.95]})
df2=df.map(partition) #how would this line work - is my doubt to be exact
即现在如何在地图函数中传递阈值?
答案 0 :(得分:1)
我们可以使用Dataframe.applymap
df2 = df.applymap(lambda x: partition(x, threshold=0.5))
或者如果只有一列:
df['probability']=df['probability'].apply(lambda x: partition(x, threshold=0.5))
但这不是必需的。您可以这样做:
df2 = df.ge(threshold).astype(int)
我建议您看到it
答案 1 :(得分:0)
您可以将lambda
用于此目的:
def partition(x,threshold):
if x<threshold:
return 0
else:
return 1
df=pd.DataFrame({'probability':[0.2,0.8,0.4,0.95]})
df['probability']=df['probability'].map(lambda x: partition(x, threshold=0.5))