首页 > 解决方案 > 将用熊猫切割的垃圾箱传递给一个函数

问题描述

我有一个数据框,如下所示:

def binning(col, cut_points, labels = None):
    '''
    From https://www.analyticsvidhya.com/blog/2016/01/12-pandas-techniques-python-data-manipulation/
    '''
    #   Define min and max values:
    minval = col.min()
    maxval = col.max()
    #   Create list by adding min and max to cut_points
    break_points = [minval] + cut_points + [maxval]

    #   If no labels provided, use default labels 0 ... (n-1)
    if not labels:
        labels = range(len(cut_points)+1)

    #   Binning using cut function of pandas
    colBin = pd.cut(col,bins=break_points,labels=labels,include_lowest=True, duplicates = 'drop')
    return colBin

cut_points = [0.5,3.5,4.5]
labels = ["z<0.5","0.5<=z<3.5","3.5<z<=4.5","z>4.5"]
sources["z_bin"] = binning(sources["z"], cut_points, labels)
print(pd.value_counts(sources["z_bin"], sort=False))

我想将每个 bin 传递给我编写的函数,以绘制散点图。我知道它pandas有绘图函数和包装器matplotlib,但如果可能的话,我想使用我的自定义函数,以保持格式与我的其他图表一致。我的自定义函数调用如下:

plotSelected(x, y, name_for_y_series, ...a couple of other arguments)

那么有什么方法可以将 y 系列与分箱的 x 值相对应吗?就像是

plotSelected(x_binned, y, name_for_y_series, ...a couple of other arguments)

我不知道如何pandas组织它的垃圾箱。它们是列表、元组还是其他东西?

标签: pandasfunctionbinning

解决方案


推荐阅读