首页 > 解决方案 > 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

标签: pythonpandasdataframerow

解决方案


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

推荐阅读