Python Forum

Full Version: Update value in sliced dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody, I'm new in python and I would ask you a question that is making me crazy.
I think I've not well understood some things, so please help me.
The question is: I want to fill NaN value of a column in a dataframe but based on a value of another column.
The example of 2 dataframe:
import pandas as pd
import numpy as np

df = pd.DataFrame([{'a':'A', 'b': 'B', 'c': 15.2},  \
                   {'a':'Z', 'b': 'M', 'c': 1.7},   \
                   {'a':'A', 'b': 'B', 'c': np.nan},\
                   {'a':'Z', 'b': 'B', 'c': 16.8},  \
                   {'a':'Z', 'b': 'M', 'c': np.nan},\
                   {'a':'A', 'b': 'M', 'c': np.nan},\
                   {'a':'Z', 'b': 'B', 'c': np.nan}])

sw = pd.DataFrame([{'x': 'B', 'v': 66.6},  \
                   {'x': 'M', 'v': 99.9},])
Now I want to fill Nan value of column named c in dataframe df depending on the value of the column b of the dataframe df and take the value from another dataframe sw, that is:
- if M then 99.9
- if B then 66.6

Here's the problem...
I try:
df.loc[(df['b'] == 'M') & (df['c'].isnull()), 'c'] = sw.loc[(sw['x']=='M'), 'v']
df.loc[(df['b'] == 'B') & (df['c'].isnull()), 'c'] = sw.loc[(sw['x']=='B'), 'v']
But the dataframe df doesn't change, Nan value still remain...

Where I'm wrong?

Thank you for answers.
sw.loc[(sw['x']=='M'), 'v']
This is a pandas series (with one value) and you can not assign this to your cell.
Just make it a value.
df.loc[(df['b'] == 'M') & (df['c'].isnull()), 'c'] = sw.loc[(sw['x']=='M'), 'v'].values
df.loc[(df['b'] == 'B') & (df['c'].isnull()), 'c'] = sw.loc[(sw['x']=='B'), 'v'].values
Output:
a b c 0 A B 15.2 1 Z M 1.7 2 A B 66.6 3 Z B 16.8 4 Z M 99.9 5 A M 99.9 6 Z B 66.6
(Nov-12-2019, 07:29 PM)ThomasL Wrote: [ -> ]...

Thank you very much ThomaL!!!