根据python中定义的intervall添加新列并插入特定值 [英] Add a new column and insert specific values according to an defined intervall in python

查看:97
本文介绍了根据python中定义的intervall添加新列并插入特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在pandas数据框中添加新列,并为所有值< = W1插入1,为所有值< = W2插入2,为所有值> W2插入3?

How to add a new column in a pandas dataframe and insert 1 for all values <=W1, 2 for all values <=W2 and 3 for all values >W2 ?

W1=3
W2=6

这是我的示例案例:

column1 number   
2       1
1       1
5       2
6       2
7       3
8       3
3       1

推荐答案

您可以将使用 cut 的另一种解决方案, 文档:

bins = [-np.inf, W1, W2, np.inf]
labels=[1,2,3]
df['d1'] = pd.cut(df['column1'], bins=bins, labels=labels)
print (df)

   column1  number  d d1
0        2       1  1  1
1        1       1  1  1
2        5       2  2  2
3        6       2  2  2
4        7       3  3  3
5        8       3  3  3
6        3       1  1  1

这篇关于根据python中定义的intervall添加新列并插入特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆