简体   繁体   English

如何对 Pandas 中每第 n 列的行进行 ffill()?

[英]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.我有一个包含 400 多列的表,我想根据第一个值每隔三列“ffill()”一次。

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根据 Top 上的第一个值,每三列 'ffill()'

在此处输入图像描述

I've already checked some of samples here but most of them are hardcoded我已经在这里检查了一些样本,但其中大部分都是硬编码的

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.顺便说一句,ffill() 仅填充列中缺失的/无值。 This is equivalent to fillna(method="ffill").这等同于 fillna(method="ffill")。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM