0

I use the following dictionary to replace missing values in a column in my dataframe:

dct = {
'Central and Eastern Europe': [
    'Albania','Bosnia and Herzegovina','Bulgaria','Croatia','Czech Republic','Estonia','Hungary','Kosovo',
    'Latvia','Lithuania','Montenegro','North Macedonia','Poland','Romania','Serbia','Slovakia','Slovenia'],
'Commonwealth of Independent States': [
    'Armenia','Azerbaijan','Belarus','Georgia','Kazakhstan','Kyrgyzstan','Moldova','Russia','Tajikistan','Turkmenistan','Ukraine','Uzbekistan'],
...
}

Now i use the following code to invert the dictionary:

revdct = {c: r for r, lst in dct.items() for c in lst}
nan = float('NaN')
df = df.set_index('Country')['Region'].fillna(revdct).reset_index()
df

df only shows the dataframe with the two columns 'Country' and 'Region' how do i get the whole dataframe printed, since it has also other columns?

Jeronimo
  • 2,268
  • 2
  • 13
  • 28
Anastasia
  • 9
  • 1
  • [How to make good reproducible pandas examples](//stackoverflow.com/q/20109391/843953) Sure, we can fabricate a dataframe with example data to test your/our code on, but wouldn't it be _so much easier_ if you just included a sample of your dataframe in your question?! – Pranav Hosangadi Mar 20 '23 at 16:22

1 Answers1

0

when you do df = df.set_index('Country')['Region'] you're reducing df to just the Region column [and Country as that's the index now].

Try filling Region in a separate statement

df = df.set_index('Country')

df['Region'] = df['Region'].fillna(revdct)
# df['Region'].fillna(revdct, inplace=True) ## [not sure it won't set off warnings]

df = df.reset_index()
df # print(df.to_markdown(tablefmt='fancy_grid'))

You could also try using .map on Country instead of setting-then-resetting index.

df['Region'] = df['Region'].fillna(df['Country'].map(revdct))
# df['Region'].fillna(df['Country'].map(revdct), inplace=True)

df

samplop

Driftr95
  • 4,572
  • 2
  • 9
  • 21
  • Thank you for your answer, but unfortunately the code didn't work. The 'Region' column didn't got filled, there are still Nan's. – Anastasia Mar 20 '23 at 10:53
  • @Anastasia sorry I forgot to move `reset_index` to after `fillna` - I've edited my answer and also added an alternative method with demonstration. Would you mind giving it another try? – Driftr95 Mar 20 '23 at 16:31
  • Thank you Driftr95! I tried .map and it worked! – Anastasia Mar 21 '23 at 11:52