我有一种方法可以从熊猫数据帧的两列计算加权平均值。由于这些列不是浮点数据类型,因此必须首先将它们转换为适当的格式。计算后,它们将转换回原始格式。
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定义此方法?
答案 0 :(得分:1)
您可以忽略警告,但是如果您不想警告 试试这个
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