首页 > 解决方案 > SAS中的proc格式相当于python

问题描述

我想

proc format; 
 value RNG

low - 24  = '1'
24< - 35  = '2'
35< - 44  = '3'
44< - high ='4'

我在 python 熊猫中需要这个。

标签: pythonpandasformat

解决方案


如果您正在寻找等效的映射功能,您可以使用类似的东西。

df = pd.DataFrame(np.random.randint(100,size=5), columns=['score'])

print(df)

输出:

   score
0     73
1     90
2     83
3     40
4     76

现在让我们对数据框中的score列应用分箱功能,并在同一数据框中创建新列。

def format_fn(x): 
    if x < 24:
        return '1'
    elif x <35:
        return '2'
    elif x< 44:
        return '3'
    else:
        return '4'

df['binned_score']=df['score'].apply(format_fn)

print(df)

输出:

   score binned_score
0     73            4
1     90            4
2     83            4
3     40            3
4     76            4

推荐阅读