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
Photo Converting Pandas DataFrame to a table of hourly blocks Abedin 1 436 Yesterday, 01:05 PM
Last Post: snippsat
  renaming a column without a name in a dataframe Carbonpony 2 933 Jan-23-2025, 08:20 AM
Last Post: Carbonpony
  Most efficient way to roll through a pandas dataframe? sawtooth500 2 1,148 Aug-28-2024, 10:08 AM
Last Post: Alice12
  docx file to pandas dataframe/excel iitip92 1 2,628 Jun-27-2024, 05:28 AM
Last Post: Pedroski55
  Adding PD DataFrame column bsben 2 1,328 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 1,986 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  unable to remove all elements from list based on a condition sg_python 3 1,703 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 1,384 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 1,454 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  pandas : problem with conditional filling of a column Xigris 2 1,413 Jul-22-2023, 11:44 AM
Last Post: Xigris

Forum Jump:

User Panel Messages

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