如何生成标签并使用它对python中的数据框列进行分类?

我是Python的新手。仍在学习列表理解。我有年龄作为连续的数字变量,我需要将其存储为0-10、10-20、20-30…90+。我将调用以下函数。我需要对数据中的100列使用不同的上下限值进行处理,这需要非常高效和简洁。有没有更好的方法可以做到这一点?

def createfactor(x,lower,upper,by,sep="-",above_char="+"):
    labs = []
    curr = lower
    while curr < upper - by:
        labs.append(str(curr) + sep + str(curr + by))
        curr = curr + by
    labs.append(str(upper - by) + above_char)
    y = pandas.cut(x,bins=numpy.linspace(lower,upper/by+1),labels=labs)
    return y
huli234 回答:如何生成标签并使用它对python中的数据框列进行分类?

您可以尝试使用pandas.cuthttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html

import pandas as pd
import numpy as np

df=pd.DataFrame({"age": [4,23,45,39,76,91,110,10],"x": [1,2,1,5,8,1]})

print(pd.merge(df,pd.cut(df["age"],bins=pd.IntervalIndex.from_tuples([(0,10),(11,20),(21,30),(31,40),(41,50),(51,60),(61,70),(71,80),(81,90),(90,np.Infinity)]),right=True,include_lowest=True),left_index=True,right_index=True,how="outer",suffixes=["","_bins"]))

输出:

age  x      age_bins
0    4  1   (0.0,10.0]
1   23  2  (21.0,30.0]
2   45  1  (41.0,50.0]
3   39  5  (31.0,40.0]
4   76  2  (71.0,80.0]
5   91  8   (90.0,inf]
6  110  1   (90.0,inf]
7   10  1   (0.0,10.0]

[Program finished]
本文链接:https://www.f2er.com/3157216.html

大家都在问