'How to ffill() the rows in every nth column in Pandas?
I have a table with 400+ columns and would like to 'ffill()' every third column based on the first value.
The data below is the result of my code:
import pandas as pd
import os
cwd = os.getcwd()
df = pd.read_excel( cwd + '/FILES/BH.xlsx' , skiprows=9)
df = df.drop(columns = ['Unnamed: 0', 'Unnamed: 1','Unnamed: 2','Unnamed: 3'])
df= df.T
df[0] = df[0].ffill()
df= df.T
print(df)
My Table
My Expected Result
this is my only problem. To 'ffill()' every third column based on the first value on Top
I've already checked some of samples here but most of them are hardcoded
Solution 1:[1]
Try this command:
df[list(df.columns)[2::3]] = df[list(df.columns)[2::3]].iloc[0]
By the way, ffill() fill only missing/None values in the column. This is equivalent to fillna(method="ffill").
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Léo Beaucourt |


