Python Forum
Update value in sliced dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Update value in sliced dataframe
#1
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.
Reply


Messages In This Thread
Update value in sliced dataframe - by bobopt - Nov-12-2019, 01:33 PM
RE: Update value in sliced dataframe - by ThomasL - Nov-12-2019, 07:29 PM
RE: Update value in sliced dataframe - by bobopt - Nov-13-2019, 07:50 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Python + Google Sheet | Best way to update specific cells in a single Update()? Vokofe 1 2,698 Dec-16-2020, 05:26 AM
Last Post: Vokofe
  Adding Sliced Positions Gizzmo28 1 1,610 Nov-05-2020, 02:46 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020