![](/img/trans.png)
[英]How to get the previous value of the same row (previous column) from the pandas dataframe?
[英]how can I get a previous row value in pandas column
我有一個這樣的df
| count | A |
|---------|---|
| yes |2 |
| yes |2 |
| total | |
| yes |2 |
| yes |2 |
| total | |
我想要一個 output 如下所示
| count | A |
|---------|---|
| yes |2 |
| yes |2 |
| total | 2 |
| yes |2 |
| yes |2 |
| total | 2 |
那就是用前一行值填充總計的A列值知道如何實現這一點
您可以嘗試使用df.loc
和series.mask
和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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.