根据列为 df 创建自定义存储桶

use*_*679 1 python pandas jupyter-notebook

我想根据价格列中的价格值添加一个带有自定义存储桶的新列(请参见下面的示例)。

  • < 400 = low
  • >=401 and <=1000 = medium
  • >1000 = expensive

桌子

product_id  price 

     2       1203       
     4        500      
     5        490       
     6        200      
     3        429       
     5        321      
Run Code Online (Sandbox Code Playgroud)

输出表

product_id  price   price_category 
 
     2       1001   high    
     4        500   medium   
     5        490   medium  
     6        200   low 
     3        429   medium  
     5        321   low
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试过的:

from numba import njit

def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x <= 50):
            bins[idx] = 1
        elif (x >= 51) & (x <= 100):
            bins[idx] = 2
        elif (x >= 101) & (x <= 250):
            bins[idx] = 3
        elif (x >= 251) & (x <= 1000):
            bins[idx] = 4
        else:
            bins[idx] = 5

    return bins

a = cut(df2['average_listings'].to_numpy())

conversion_dict = {1: 'S',
                   2: 'M',
                   3: 'L',
                   4: 'XL',
                   5: 'XXL'}

bins = list(map(conversion_dict.get, a))

Run Code Online (Sandbox Code Playgroud)

--> 但我正在努力将其添加到主 df 中

ALo*_*llz 5

pandas有它自己的cut方法。指定箱的右边缘和相应的标签。

df['price_category'] = pd.cut(df.price, [-np.inf, 400, 1000, np.inf],
                              labels=['low', 'medium', 'high'])

   product_id  price price_category
0           2   1203           high
1           4    500         medium
2           5    490         medium
3           6    200            low
4           3    429         medium
5           5    321            low
Run Code Online (Sandbox Code Playgroud)

如果没有labels参数,您将返回用于数据的确切容器(默认情况下是闭包),在本例中是:

Categories (3, interval[float64]): [(-inf, 400.0] < (400.0, 1000.0] < (1000.0, inf]]
Run Code Online (Sandbox Code Playgroud)