【问题标题】:How to fill a particular value with mean value of the column between first row and the corresponding row in pandas dataframe如何用熊猫数据框中第一行和相应行之间的列的平均值填充特定值
【发布时间】:2019-01-05 16:50:16
【问题描述】:

我有一个这样的df,

A   B   C   D   E
1   2   3   0   2
2   0   7   1   1
3   4   0   3   0
0   0   3   4   3

我正在尝试将第一行和对应列的 0 值行之间的所有 0 替换为 mean() 值,

我的预期输出是,

A       B       C           D       E
1.0     2.00    3.000000    0.0     2.0
2.0     1.00    7.000000    1.0     1.0
3.0     4.00    3.333333    3.0     1.0
1.5     1.75    3.000000    4.0     3.0

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    如果每列有多个0,则主要问题需要先前的mean 值,因此创建矢量化解决方案确实有问题:

    def f(x):
        for i, v in enumerate(x):
            if v == 0: 
                x.iloc[i] = x.iloc[:i+1].mean()
        return x
    
    df1 = df.astype(float).apply(f)
    print (df1)
    
         A     B         C    D    E
    0  1.0  2.00  3.000000  0.0  2.0
    1  2.0  1.00  7.000000  1.0  1.0
    2  3.0  4.00  3.333333  3.0  1.0
    3  1.5  1.75  3.000000  4.0  3.0
    

    更好的解决方案:

    #create indices of zero values to helper DataFrame
    a, b = np.where(df.values == 0)
    df1 = pd.DataFrame({'rows':a, 'cols':b})
    #for first row is not necessary count means
    df1 = df1[df1['rows'] != 0]
    print (df1)
       rows  cols
    1     1     1
    2     2     2
    3     2     4
    4     3     0
    5     3     1
    
    #loop by each row of helper df and assign means
    for i in df1.itertuples():
        df.iloc[i.rows, i.cols] = df.iloc[:i.rows+1, i.cols].mean()
    
    print (df)
         A     B         C  D    E
    0  1.0  2.00  3.000000  0  2.0
    1  2.0  1.00  7.000000  1  1.0
    2  3.0  4.00  3.333333  3  1.0
    3  1.5  1.75  3.000000  4  3.0
    

    另一个类似的解决方案(所有对中的mean):

    for i, j in zip(*np.where(df.values == 0)):
        df.iloc[i, j] = df.iloc[:i+1, j].mean()
    print (df)
    
         A     B         C    D    E
    0  1.0  2.00  3.000000  0.0  2.0
    1  2.0  1.00  7.000000  1.0  1.0
    2  3.0  4.00  3.333333  3.0  1.0
    3  1.5  1.75  3.000000  4.0  3.0
    

    【讨论】:

    • 感谢 jezrael 的新解决方案,我将对其进行测试并批准 (y)
    【解决方案2】:

    IIUC

    def f(x):
        for z in range(x.size):
            if x[z] == 0: x[z] = np.mean(x[:z+1])
        return x
    
    df.astype(float).apply(f)
    
        A   B       C           D   E
    0   1.0 2.00    3.000000    0.0 2.0
    1   2.0 1.00    7.000000    1.0 1.0
    2   3.0 4.00    3.333333    3.0 1.0
    3   1.5 1.75    3.000000    4.0 3.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多