1

I have a dataframe:

id    val    size
1      100
2      500
3      300

i have a nested list L = [[300,20],[100,45],[500,12]]

I want to fill my dataframe with 2nd element in my sublist, corresponding to that column value.

i.e my final dataframe should look like

id    val    size
1      100   45
2      500   12
3      300   20
2
  • What did you try so far? Commented Aug 24, 2017 at 9:19
  • 1
    @cᴏʟᴅsᴘᴇᴇᴅ Yes :) Commented Sep 11, 2017 at 11:10

2 Answers 2

1

Another way using merge

In [1417]: df.merge(pd.DataFrame(L, columns=['val', 'size']), on='val')
Out[1417]:
   id  val  size
0   1  100    45
1   2  500    12
2   3  300    20
Sign up to request clarification or add additional context in comments.

Comments

0

First initialise a mapping:

In [132]: mapping = dict([[300,20],[100,45],[500,12]]); mapping
Out[132]: {100: 45, 300: 20, 500: 12}

Now, you can use either df.replace or df.map.


Option 1

Using df.replace:

In [137]: df['size'] = df.val.replace(mapping)

In [138]: df
Out[138]: 
   id  val  size
0   1  100    45
1   2  500    12
2   3  300    20

Option 2

Using df.map:

In [140]: df['size'] = df.val.map(mapping)

In [141]: df
Out[141]: 
   id  val  size
0   1  100    45
1   2  500    12
2   3  300    20

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.