1

Edited several times to match SO standard

I have a DataFrame with 2 columns: id, label. And I also have generated labels for some of the ids, so I have a dictionary 'new_labels', which stores label values for some ids. What is the best way of filling these values into the DF?

import pandas as pd

df = pd.DataFrame({'id': ['A', 'B', 'C', 'D', 'E', 'F'], 
                   'label': ['yes', 'no', None, None, None, 'yes']})
new_labels = {'D':'yes', 'E':'no'}
In [1]: df
Out[1]:
    id  label
0   A   yes
1   B   no
2   C   None
3   D   None
4   E   None
5   F   yes

And after inserting the new_labels I expect my df to change as such:

In [3]: df
Out[3]:
    id  label
0   A   yes
1   B   no
2   C   None
3   D   yes
4   E   no
5   F   yes
  • It's best to show a small example dataset and your dictionary. – Erfan Feb 15 '20 at 15:13
  • @Erfan added as images! – Mathemmagician Feb 15 '20 at 15:24
  • 1
    Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) also [Please don't post images of code/data (or links to them)](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question) – anky Feb 15 '20 at 15:25
  • @anky_91 I apologize for bad practice, hopefully new edit matches the standards – Mathemmagician Feb 15 '20 at 15:45
  • You want: `df['label'] = df['id'].map(new_labels).fillna(df['label'])` – Erfan Feb 15 '20 at 15:46
  • @Erfan Thanks, this line is correct. However, I don't think that I'm asking the same question as to the one you marked since there the dictionary keys and new values (in the link ) refer to the same column, while mine are different columns (which is what you have) – Mathemmagician Feb 15 '20 at 16:15

0 Answers0