Update value in sliced dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Update value in sliced dataframe (/thread-22429.html) |
Update value in sliced dataframe - bobopt - Nov-12-2019 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. RE: Update value in sliced dataframe - ThomasL - Nov-12-2019 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
RE: Update value in sliced dataframe - bobopt - Nov-13-2019 (Nov-12-2019, 07:29 PM)ThomasL Wrote: ... Thank you very much ThomaL!!! |