Ajay Chinni
Ajay Chinni

Reputation: 840

How to give column name dynamicaly in pandas assign

I have a dataFrame with two columns

lst = [['James',15],['Michael',10]]
df1 = pd.DataFrame(lst,columns = ['name','val'])

I only want to use pandas assign function to do the bellow task

col = 'val'
df1 = df1.assign(col=lambda x: x.val+10)

Which gives me this output

      name  val  col
0    James   25   35
1  Michael   20   30

But i actually want this

      name  val
0    James   25
1  Michael   20 

I want to pass the column name val in col variable

Upvotes: 1

Views: 101

Answers (1)

Dishin H Goyani
Dishin H Goyani

Reputation: 7693

It accept *kwargs keyword argument. So you can make first dictionary and then unpack using **.

col = 'val'
df1 = df1.assign(**{col:lambda x: x.val+10})
df1
      name  val
0    James   25
1  Michael   20

Upvotes: 2

Related Questions