1

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

4
  • Is it on purpose that col is missing ? Commented Aug 13, 2020 at 12:43
  • col = 'val' i just wanted to do the addition on column val. assign is taking col as a column name but i want it as a variable and pass val Commented Aug 13, 2020 at 12:52
  • @AjayChinni You are using [15,10] in initial df1 so expected output would be [25,20] please update question accordingly. Commented Aug 13, 2020 at 12:59
  • 1
    @DishinHGoyani Thanks for understanding my question and even correcting it. Perfect Commented Aug 13, 2020 at 13:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.