Bottom Page

• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 Update value in sliced dataframe bobopt Unladen Swallow Posts: 2 Threads: 1 Joined: Nov 2019 Reputation: 0 Likes received: 0 #1 Nov-12-2019, 01:33 PM (This post was last modified: Nov-12-2019, 01:33 PM by bobopt. Edited 1 time in total.) 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. ThomasL Minister of Silly Walks Posts: 361 Threads: 5 Joined: Jun 2019 Reputation: 64 Likes received: 84 #2 Nov-12-2019, 07:29 PM `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`````` bobopt Unladen Swallow Posts: 2 Threads: 1 Joined: Nov 2019 Reputation: 0 Likes received: 0 #3 Nov-13-2019, 07:50 AM (Nov-12-2019, 07:29 PM)ThomasL Wrote: ... Thank you very much ThomaL!!! « Next Oldest | Next Newest »

Top Page

Forum Jump:

Users browsing this thread: 1 Guest(s)