Ris*_*Rao 7 python apply dataframe python-3.x pandas
假设我有一个包含概率列的数据框。现在我创建一个映射函数,如果概率大于阈值,则返回 1,否则返回 0。现在的问题是,我想通过将阈值作为函数的参数来指定阈值,然后将其映射到熊猫数据框。
以下面的代码为例:
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)
我的问题是,最后一行如何工作,即如何在地图函数内传递阈值?
我们可以用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