[英]Creating new column with ranges based on existing column
我有一列具有不同的值。 我想创建一个新列,将这些值分组到范围内(例如 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
您的问题有问题:边界 class 值会发生什么? 5 属于 0-5 class 还是属于 5-10 class?
无论如何,你最好的选择可能是这样的。 我假设您的课程如下: ]-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.