Home > OS >  How to ffill() the rows in every nth column in Pandas?
How to ffill() the rows in every nth column in Pandas?

Time:04-15

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

enter image description here

My Expected Result

this is my only problem. To 'ffill()' every third column based on the first value on Top

enter image description here

I've already checked some of samples here but most of them are hardcoded

CodePudding user response:

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").

  • Related