簡體   English   中英

基於現有列創建具有范圍的新列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM