pandas - 我想在 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]
解决方案
如果您想使用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
推荐阅读
- spring - Spring Boot 反应式(webflux)监控与监控普通 Spring Boot MVC 有什么不同吗?
- javascript - 如何通过函数参数发送 POST 数据?
- excel - EXCEL 公式 - 索引匹配、大型和多个标准
- pandas - 如何根据循环的值添加数据框列
- dart - 如何实现一个在mixin上使用的类?
- logging - 格式化 loki 日志流 - 错误:loghttp.PushRequest.Streams
- cordova - 如何在生产中使用 socketio 和 cordova 混合应用程序?
- ios - 苹果证书吊销
- dictionary - Julia:在目标函数中使用字典值?
- arduino - Arduino - 未检测到 USB 设备