python - 熊猫 | 替代 lambda 函数 => .loc[row_indexer,col_indexer] = value
问题描述
我有一种方法可以从熊猫数据框的两列中计算加权平均值。由于这些列不是浮点数据类型,因此必须首先将它们转换为适当的格式。在计算之后,它们被转换回原始格式。
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 定义此方法?
解决方案
你可以忽略警告,但如果你不想警告试试这个
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
推荐阅读
- php - 注意:未定义变量:array_push,函数名必须是字符串
- wikipedia-api - 获取维基媒体中特定类别的所有图像
- java - 从 Jython 访问受保护的 Java 属性
- android - Android - 出现新的快餐栏时如何保持粘性快餐栏?
- git - 将更改应用到另一个分支 git
- java - 插入新记录时传递到持久错误的分离实体
- condor - Condor 使用 cctools/work_queue 提交给 OSG
- firebase - 如何将 Firestore 文档列表绑定到 Flutter 中的下拉菜单?
- android - 保持 ViewPager 元素的最大高度相同
- solr - 修改停用词列表