我有一个方法可以计算两列熊猫数据帧的加权平均值。由于这些列不是float数据类型,因此必须首先将它们转换为适当的格式。计算后,它们将转换回原始格式。
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对于转换,我使用Lambda函数,它会生成一条警告消息:
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我如何用.loc定义这个方法?
发布于 2020-08-11 04:23:35
您可以忽略该警告,但如果您不想要警告,请尝试执行以下操作
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_averagehttps://stackoverflow.com/questions/63347379
复制相似问题