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:
- if M then 99.9
- if B then 66.6
Here's the problem...
I try:
Where I'm wrong?
Thank you for answers.
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.
