Lostsoul
Lostsoul

Reputation: 25991

How can I create dynamic column names in Pandas?

I have a list of numerical columns [NumColumns] and I want to Bin all of them but I also want to keep the original value in the data frame as well so I don't want the values simply replaced. How can I do that?

I tried this(which works to replace) -

data[NumColumns] = pd.cut(data[NumColumns], bins=[0,30,70,100], labels=["Low", "Mid", "High"])

Instead of replacing, I'm hoping it would add '_bin' to the end so I would end up with something like value_bin, revenue_bin, age_bin, etc..

I'm not sure how to do this as I have to declare this on the left-hand side. I'm wondering if there is a common way?

Upvotes: 2

Views: 191

Answers (1)

jezrael
jezrael

Reputation: 862481

I think the simpliest is use f-strings:

for c in NumColumns:
    data[f'{c}_bin'] = pd.cut(data[c], bins=[0,30,70,100], labels=["Low", "Mid", "High"])

Upvotes: 2

Related Questions