简体   繁体   中英

Pandas | Alternative for lambda function => .loc[row_indexer,col_indexer] = value instead

I have a method that calculates a weighted average from two columns of a pandas dataframe. Since these columns are not of the float datatype, they have to be converted into the appropriate format first. After the calculation they are converted back to the original format.

def calculate_weighted_average(self, dataframe, column_for_average, column_for_weight):
    a = dataframe[column_for_average]
    w = dataframe[column_for_weight]
    # convert german decimal to float
    a = a.apply( lambda x : self.convert_german_decimal_to_float(x) )
    # calulate average
    weighted_average = (a * w).sum() / w.sum()
    # convert float to german decimal 
    weighted_average = self.convert_float_to_german_decimal(weighted_average)
    return weighted_average

For the conversion I use Lambda function, which generates a warning message:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

How can I define this method with.loc?

You can Ignore the Warning, But if you don't want warning try this

def calculate_weighted_average(self, dataframe, column_for_average, column_for_weight):
    a = dataframe[column_for_average]
    w = dataframe[column_for_weight]
    # convert german decimal to float
    a1 = a.apply( lambda x : self.convert_german_decimal_to_float(x))
    # calulate average
    weighted_average = (a1 * w).sum() / w.sum()
    # convert float to german decimal 
    weighted_average = self.convert_float_to_german_decimal(weighted_average)
    return weighted_average

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM