Search code examples
pythonpandasdataframeapplydata-analysis

How can perform an pandas apply method on Dataframe?


The problem is that i am tackling to convert Organisations by NumberOfSpaceMission. If number of space mission smaller than particular value the new column important_organisation will be 'Other countries' otherwise it will be organisation's name which is index of dataframe.

Our Dataframe

def editCountry(row):
    if row['NumberofSpaceMission'] < 10:
       return 'Other organisation'
    return row.index

new_df['important_organisations'] = new_df.apply(editCountry)

I tried some structure and ways using apply method.Moreover i employed with map function.


Solution

  • First create a default value:

    new_df['important_organisations'] = 'Other organisation'
    

    Then use pandas filtering to get the index values & assign to the respective rows:

    new_df.loc[new_df['NumberofSpaceMission']>=10,'important_organisations'] = new_df.loc[new_df['NumberofSpaceMission']>=10].index