Python Forum
How to assign a value to pandas dataframe column rows based on a condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to assign a value to pandas dataframe column rows based on a condition
#1
Hello,

I want to assign a value in "Value" column into a new column and up to all next empty rows until next value comes. My expected value is available in a new column 'Expected_Value'.

import pandas as pd

df2 = pd.DataFrame({ 'Value':['Second', np.nan, np.nan, 'Fourth', np.nan],
                    'Name':['John', 'Tom', 'Tom', 'Tom','One'],
                    'Expected_Value':['Second', 'Second', 'Second', 'Fourth', 'Fourth']
                    })



I tried this using two functions (apply lambda & assign lambda), however, there were error messages as follows.

apply lambda method
df2['new_value'] = np.nan

df2['new_value'] = df2.apply(lambda row: row['Value'] if (~pd.isna(row['Value'])) else row['new_value'].shift(-1)) 

# KeyError: 'Value'
Assign lambda method
del df2['new_value']
df2 = df2.assign(new_value=lambda x: (x['Value']) if (~(x['Value'].isna())) else x['new_value'].shift(-1))
# ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
Appreciate it if someone could help with this.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Adding PD DataFrame column bsben 2 320 Mar-08-2024, 10:46 PM
Last Post: deanhystad
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 286 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  unable to remove all elements from list based on a condition sg_python 3 450 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 743 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 704 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  pandas : problem with conditional filling of a column Xigris 2 636 Jul-22-2023, 11:44 AM
Last Post: Xigris
  Question on pandas.dataframe merging two colums shomikc 4 837 Jun-29-2023, 11:30 AM
Last Post: snippsat
  Sent email based on if condition stewietopg 1 866 Mar-15-2023, 08:54 AM
Last Post: menator01
  Pandas AttributeError: 'DataFrame' object has no attribute 'concat' Sameer33 5 5,673 Feb-17-2023, 06:01 PM
Last Post: Sameer33
  Difference one column in a dataframe Scott 0 642 Feb-10-2023, 08:41 AM
Last Post: Scott

Forum Jump:

User Panel Messages

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