How do I solve this kind of problem through pandas.cut()?

Viewed 31

I have my data as

data = pd.DataFrame({'A':[3,50,50,60],'B':[49,5,37,59],'C':[15,34,43,6],'D':[35,39,10,25]})

If I use cut this way

p = ['A','S','T','U','V','C','Z']
bins = [0,30,35,40,45,50,55,60]
data['A*'] = pd.cut(data.A,bins,labels=p)
print(data)

I get

    A   B   C   D  A*
0   3  49  15  35  A
1  50   5  34  39  V
2  50  37  43  10  V
3  60  59   6  25  Z

How would I cut it to get

    A   B   C   D  A*
0   3  49  15  35  3A
1  50   5  34  39  50V
2  50  37  43  10  50V
3  60  59   6  25  60Z

I tried this but doesn't work

for x in data.A:
    p = [str(x)+'A',str(x)+'S',str(x)+'T',str(x)+'U',str(x)+'V',str(x)+'C',str(x)+'Z']
bins = [0,30,35,40,45,50,55,60]

It gives me this

    A   B   C   D  A*
0   3  49  15  35  60A
1  50   5  34  39  60V
2  50  37  43  10  60V
3  60  59   6  25  60Z
1 Answers

Convert column A to strings and categoricals from pd.cut too and join together:

p = ['A','S','T','U','V','C','Z']
bins = [0,30,35,40,45,50,55,60]
data['A*'] = data.A.astype(str) + pd.cut(data.A,bins,labels=p).astype(str)
print(data)
    A   B   C   D   A*
0   3  49  15  35   3A
1  50   5  34  39  50V
2  50  37  43  10  50V
3  60  59   6  25  60Z

EDIT:

For processing all columns is possible use DataFrame.apply:

data = data.apply(lambda x: x.astype(str) + pd.cut(x,bins,labels=p).astype(str))
print(data)
     A    B    C    D
0   3A  49V  15A  35S
1  50V   5A  34S  39T
2  50V  37T  43U  10A
3  60Z  59Z   6A  25A
Related