首页 > 解决方案 > 我想在 pandas Dataframe 中使用 shift 函数来归档缺失值

问题描述

我想在 pandas Dataframe 中使用 shift 函数来归档缺失值..

我尝试:

ex_df = pd.DataFrame({'a': [1,4,7,3,5],'b': [4, 5,8,2,6],'c': [0, 0,1,1,0],'d':[3,np.nan,9,np.nan,np.nan]})
print(ex_df)

ex_df.info()
print(type(ex_df['a']))
ex_df['d'] = ex_df.apply(
    lambda row: row['a'].shift(1)*row['b'].shift(1) if pd.isnull(row['d']) else row['d'],
    axis=1
)

得到错误:

[![AttributeError: 'numpy.float64' object has no attribute 'shift' ][1]][1]

在此处输入图像描述

标签: pandasdataframeapplyshift

解决方案


如果您想使用apply方法,那么以下应该可以工作。您只需要在应用的args参数中传递您移动的数据帧/系列。

ex_df['d'] = ex_df.apply(
    lambda row,a_s,b_s: a_s[row.name]*b_s[row.name] if pd.isnull(row['d']) else row['d'],
    axis=1,
    args = [ex_df['a'].shift(1),ex_df['b'].shift(1)]
)

ex_df

输出:

    a   b   c   d
0   1   4   0   3.0
1   4   5   0   4.0
2   7   8   1   9.0
3   3   2   1   56.0
4   5   6   0   6.0

推荐阅读