- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
创建一个 lambda 函数来计算加权平均值并将其发送到字典。
wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS'])
# Define a dictionary with the functions to apply for a given column:
f = {'DRESS_AMT': 'max',
'FACE_AMT': 'sum',
'Other_AMT': {'weighted_mean' : wm}}
# Groupby and aggregate with dictionary:
df2=df.groupby(['ID','COL1'], as_index=False).agg(f)
此代码有效,但如果权重加起来为 0 ZeroDivisionError
,则加权平均 lambda 函数将失败。在这些情况下,我希望输出“Other_AMT”仅为 0。
我阅读了一篇关于使用 np.ma.average(屏蔽平均)的文档,但无法理解如何实现它
最佳答案
这还不够吗?
def wm(x):
try:
return np.average(x, weights=df.loc[x.index, 'WEIGHTS'])
except ZeroDivisionError:
return 0
f = {'DRESS_AMT': 'max',
'FACE_AMT': 'sum',
'Other_AMT': {'weighted_mean' : wm} }
df2=df.groupby(['ID','COL1'], as_index=False).agg(f)
关于python - Pandas/numpy 加权平均 ZeroDivisionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49864679/
我需要更改利率列的总数。我的意思是,比率列中的总数是汇总,我需要加权平均值而不是总数。例如: 数量…………率 450000.......8.75 390000.......8 15000.......
我有一个包含林分编号、树种、高度和体积的数据框: import pandas as pd df=pd.DataFrame.from_items([('STAND_ID',[1,1,2,3,3,3]),
使用 NumPy 的加权平均值,我希望一个具有无限权重的元素支配结果,但它返回 NaN, >>> np.average([1,2], weights=[np.inf, 1]) nan 这是故意设计的吗
我经常在 Python 列表中添加/删除元组,并且对加权平均值(而不是列表本身)感兴趣。由于与其余部分相比,这部分在计算上非常昂贵,因此我想对其进行优化。跟踪加权平均值的最佳方法是什么?我可以想到两种
创建一个 lambda 函数来计算加权平均值并将其发送到字典。 wm = lambda x: np.average(x, weights=df.loc[x.index, 'WEIGHTS']) # D
我是一名优秀的程序员,十分优秀!