【问题标题】:Pandas pivot table ignoring zeros while taking mean熊猫数据透视表在取平均值时忽略零
【发布时间】:2016-06-23 14:23:32
【问题描述】:

我正在尝试以下方法

import pandas as pd
import numpy as np

dfout3 = pd.DataFrame({'Idx': MnthIdx,
                       'Col1': Val1,
                       'Col2': Val2,
                       'Col3': Val3)})

MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Col1','Col2','Col3'], aggfunc=[np.mean])

但我想在取每个值的平均值时忽略零。有没有办法通过熊猫而不是我为零做索引并摆脱它们并取列的平均值?

【问题讨论】:

  • 既然你标记了 numpy... a = np.array([0,1,0,2,0,3]) 然后 np.where(a>0,a,np.nan)产生 array([nan, 1.000, nan, 2.000, nan, 3.000]) 所以把它和 nanmean... np.nanmean(np.where(a>0,a,np.nan)) 产生 2.0

标签: python numpy pandas pivot-table


【解决方案1】:

我不知道是否有办法忽略零,但您可以将它们设置为 pivot 之前的平均值(这将给出相同的结果):

for col in dfout3.columns:
    dfout3.ix[dfout3.col == 0,col] = dfout3.col.mean()

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 2021-02-28
    • 2023-01-11
    • 1970-01-01
    • 2021-08-20
    • 2015-07-30
    • 1970-01-01
    • 2018-05-15
    相关资源
    最近更新 更多