search

Home  >  Q&A  >  body text

python - pandas dataframe如何对某列的空数据位置进行update?update的函数是自定义的,参数是同一行的另外两列数据

dataframe的某列fillna如何通过自定义函数的返回值进行填充?自定义函数需要以某几列数据作为参数。类似下面代码的功能怎么实现?df['resultOfab'].fillna(myFunc(df['acolumn'],df['bcolumn']))

貌似只有dataframe才有fillna函数,而且只能指定值作为填充。要么就是只能加减乘除某两列得到新列数据。如果全部重新计算效率又很低。

迷茫迷茫2778 days ago1285

reply all(1)I'll reply

  • 迷茫

    迷茫2017-04-18 10:23:42

    Is it like this? It's a little unclear what to do. . .

    >>> df
         0    1    2
    0  1.0  NaN  5.0
    1  2.0  3.0  6.0
    2  3.0  5.0  7.0
    3  4.0  NaN  8.0
    >>> def dfunc(df1, df2):
    ...     return df1 + 2 * df2
    ...
    >>> df[1] = df[1].fillna(dfunc(df[0], df[2]))
    >>> df
         0     1    2
    0  1.0  11.0  5.0
    1  2.0   3.0  6.0
    2  3.0   5.0  7.0
    3  4.0  20.0  8.0
    

    Or like this?

    >>> df
         0    1    2
    0  1.0  NaN  5.0
    1  2.0  3.0  6.0
    2  3.0  5.0  7.0
    3  4.0  NaN  8.0
    
    >>> def d_func(df1, df2):
    ...     return df1 + df2 * 2
    ...
    
    >>> df[1] = np.where(df[1].isnull(), d_func(df[0], df[2]), df[1])
    
    >>> df
         0     1    2
    0  1.0  11.0  5.0
    1  2.0   3.0  6.0
    2  3.0   5.0  7.0
    3  4.0  20.0  8.0
    

    This is vector type a?b:c

    reply
    0
  • Cancelreply