问题描述
我想在 Pandas Dataframe 中使用 shift 函数来归档缺失值..
我尝试:
if
ex_df = pd.DataFrame({'a': [1,4,7,3,5],'b': [4,5,8,2,6],'c': [0,1,0],'d':[3,np.nan,9,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
)
解决方法
以这种方式使用 apply 函数,它作用于特定的行值而不是序列或数据帧,因此它无法访问 shift 命令。
它需要被写入,以便 shift 命令正在执行系列。
试试这样的方法。
df['d']=df['d'].fillna(df[['a','b']].shift(1).sum(axis=1))
,
如果您想使用 apply
方法,那么以下应该可以工作。您只需要在 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