python - how can I get a previous row value in pandas column
问题描述
I have a df like this
| count | A |
|---------|---|
| yes |2 |
| yes |2 |
| total | |
| yes |2 |
| yes |2 |
| total | |
I want a output like below
| count | A |
|---------|---|
| yes |2 |
| yes |2 |
| total | 2 |
| yes |2 |
| yes |2 |
| total | 2 |
that is fill the A column values where there is total with the previous row value any idea how can I achieve this
解决方案
You can try with df.loc
and series.mask
and ffill
df.loc[df['count'].eq("total"),"A"] = df['A'].mask(df['A'].eq('')).ffill()
print(df)
count A
0 yes 2
1 yes 2
2 total 2
3 yes 2
4 yes 2
5 total 2
推荐阅读
- javascript - 使用 php 循环 WordPress 的响应框布局
- python - 无法在 QVBoxLayout 中对齐顶部 QTableWidget
- angular - 如何使用 Angular 8 设置 PhantomJS?----> 切换到 Puppeteer
- android - 如何访问未计算或不存在于android显示屏上的布局
- html - 如何在 Angular 6 和 .NET 核心中按 Id 设置表单中的值?
- arduino-esp8266 - 如何使用 mkspiffs 和 esptool 正确下载 SPIFFS bin
- pagespeed-insights - PageSpeedInsights 结果 URL
- kubernetes - 如何在 Kubernetes 中更改请求路径
- azure - 如何在 Azure ML Studio 中使用预训练的 TF 模型
- squish - 如何在 squish Qt 中生成自定义 XML 报告?