How to apply the same function with different input arguments to create new columns in pandas dataframe?

前端 未结 1 1457
礼貌的吻别
礼貌的吻别 2020-12-22 04:07

So i\'ve this sample dataframe:

      x_mean    x_min    x_max     y_mean     y_min     y_max
 1      85.6        3      264       75.7         3       240
          


        
相关标签:
1条回答
  • 2020-12-22 05:02

    This is the concept that you need to follow to make this happen. First you need to have your ranges stored in a dictionary to enable access to them through names.

    range_dict = {}
    range_dict['x_range'] = x_range
    range_dict['y_range'] = y_range
    

    Also, you need to have the columns that you need to do the calculation for in a list (or you can use regex to get those if they have a specific pattern)

    mean_cols_list = ['x_mean', 'y_mean']
    

    Now, to apply your function over all columns, you need to define a function like this

    def min_max_calculator(df, range_dictionary, mean_columns_list):
        for i in range(len(mean_cols_list)):
            # this returns 'x_mean'
            current_column = mean_cols_list[i]
            # this returns 'x_min_max_value'
            output_col_name = current_column.replace('mean','min_max_value')
            # this returns 'x_range'
            range_name = current_column.replace('mean','range')
            # this returns the list of ranges for x_range
            range_list = range_dict[range_name]
            # This add the calculated column to the dataframe
            df[output_col_name] = df[current_column].apply(lambda x: min_max_range(x,range_list))
        return(df)
    
    df_output = min_max_calculator(df, range_dict, mean_cols_list)
    
    0 讨论(0)
提交回复
热议问题