[英]Creating new column with ranges based on existing column
I have one column with different values.我有一列具有不同的值。 I would like to make a new column that will group those values into ranges (eg. 0-5, 5-10, 10-20, etc.) How should I do it using pandas library?
我想创建一个新列,将这些值分组到范围内(例如 0-5、5-10、10-20 等)。我应该如何使用 pandas 库来做到这一点?
df['price_group']
0 475000
1 720000
2 232000
3 728000
4 706000
...
21615 485000
21616 1008000
21617 283000
21618 293550
21619 250000
Something wrong with your question: what happens with boundary class values?您的问题有问题:边界 class 值会发生什么? Does 5 belong to the 0-5 class or to the 5-10 class?
5 属于 0-5 class 还是属于 5-10 class?
Anyways, your best bet would probably be something like this.无论如何,你最好的选择可能是这样的。 I'm assuming your classes are the following ones: ]-inf, -1] , [0, 4] , [5, 9] , [10, 19] and [20, inf[
我假设您的课程如下: ]-inf, -1] , [0, 4] , [5, 9] , [10, 19]和[20, inf[
import pandas as pd
# Declare your function
def my_custom_function(length):
""" you could also return int, float or other objects"""
if length < 0:
return "negative"
elif length < 5:
return "0m - 4m"
elif length < 10:
return "5m - 9m"
elif length < 20:
return "10m - 19m"
else:
return "20m and +"
# Add your desired column
df['sampled_length'] = df['length'].apply(lambda x: my_custom_function(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.