Creating Multiple columns based on condition in a dataframe

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ck25python
    New Member
    • Jan 2020
    • 20

    Creating Multiple columns based on condition in a dataframe

    Hi There,

    I am very new to python environment.
    I am trying to replicate one of the SAS code in python.
    I want to create 3 columns based on multiple conditions:

    Below are the requirements:

    if year is 2019 i want to create a column as en2019 and assign value as 1 else assign value as 0
    same goes for year 2020.

    Another condition is

    if year=comm_year (2019=2019) then create a column 'commencing'and assign value as 'commencing' else assign value as 'Re-Enrolling'.

    For your reference, I have attached the word document of SAS function and output which I am trying to replicate it in python.

    Below is the data frame:

    Code:
    data = {'year': [2019, 2020, 2019, 2020, 2019],
                   'comm_year': [2019, 2019, 2020, 2020, 2019],
           'count':[1,1,1,1,1]}
    enrol = pd.DataFrame(data, columns = ['year','comm_year','count'])
    enrol
    Please advise on this.
    Thanks.
    Attached Files
  • SioSio
    Contributor
    • Dec 2019
    • 272

    #2
    To get the values ​​of multiple columns from pandas.DataFram e together, it can use the built-in function zip() for faster execution.
    Code:
    import pandas as pd
    data = {'year': [2019, 2020, 2019, 2020, 2019],
            'comm_year': [2019, 2019, 2020, 2020, 2019],
            'count':[1,1,1,1,1]}
    enrol = pd.DataFrame(data, columns = ['year','comm_year','count'])
    enrol
    
    enrol_19=[]
    enrol_20=[]
    commencing=[]
    
    for year, comm_year, count in zip(enrol['year'], enrol['comm_year'], enrol['count']):
        if year == 2019:
            enrol_19.append(count)
        else:
            enrol_19.append(0)
        if year == 2020:
            enrol_20.append(count)
        else:
            enrol_20.append(0)
        if year == comm_year:
            commencing.append('Commencing')
        else:
            commencing.append('Re_Enrolling')
    
    enrol["enrol_19"]=enrol_19
    enrol["enrol_20"]=enrol_20
    enrol["Commencing"]=commencing
    
    print(enrol)

    Comment

    • madankarmukta
      Contributor
      • Apr 2008
      • 308

      #3
      What is the current output that you are getting?? Can you help us with that ??

      Thanks

      Comment

      Working...