Python Forum
create new column based on condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
create new column based on condition
#11
you haven't gone to the code Wink
Reply
#12
Oops my bad.. I was looking at the previous post and trying to understand Tongue Tongue Big Grin
Reply
#13
Expansion and explanation on my code version. Here we use the dataframe "apply" function to apply a function to the dataframe

import pandas as pd

def my_transform(x): #function to be applied to the dataframe
    if x[0]>4: # refer to dataframe as "x". Test if first column is >4
        return x[0] # if >4, return that value
    else: #otherwise
        return x[1] #return the value from the second column

df = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]]) #create a simple dataframe with 3 rows and 3 columns
df[3] = df.apply(my_transform, axis=1) #calls the function above, apply "by row" rather than by column (axis value)
df #display result
Output:
0 1 2 3 0 1 2 3 2 1 4 5 6 5 2 7 8 9 7
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 289 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  unable to remove all elements from list based on a condition sg_python 3 458 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Create dual folder on different path/drive based on the date agmoraojr 2 458 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 747 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  Sent email based on if condition stewietopg 1 869 Mar-15-2023, 08:54 AM
Last Post: menator01
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 849 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Python create a spreadsheet with column and row header ouruslife 4 1,650 Jul-09-2022, 11:01 AM
Last Post: Pedroski55
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 1,532 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Openpyxl-change value of cells in column based on value that currently occupies cells phillipaj1391 5 9,869 Mar-30-2022, 11:05 PM
Last Post: Pedroski55
  Cannot convert the series to <class 'int'> when trying to create new dataframe column Mark17 3 8,551 Jan-20-2022, 05:15 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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