如何在Pandas数据框中使用多列替换单元格?

4

我有一个包含多列的数据框,我想用一次操作将列中的0替换为该列中的前一个值。

使用df['A'].replace(to_replace=0, method='ffill')可以实现,但只要是所有数据框就会抛出错误,可能是因为to_replace不是系列数据。

我该怎么做?

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=4, freq='D')

columns = ['A','B', 'C']
data = np.array([[1, 2, 2], [3, 0, 5], [0, 4, 0], [3, 4, 5]])
df = pd.DataFrame(data, index=index, columns=columns)
df
Out[333]: 
            A  B  C
2018-07-16  1  2  2
2018-07-17  3  0  5
2018-07-18  0  4  0
2018-07-19  3  4  5

# Throws an error here :

df.replace(to_replace=0, method='ffill')
TypeError: cannot replace [0] with method ffill on a DataFrame

# Works column by column :

df['A'].replace(to_replace=0, method='ffill')
Out[338]: 
2018-07-16    1
2018-07-17    3
2018-07-18    3
2018-07-19    3
Freq: D, Name: A, dtype: int64
2个回答

3

可能是这样:

print(df.replace(0,np.nan).ffill())

输出:

              A    B    C
2018-07-16  1.0  2.0  2.0
2018-07-17  3.0  2.0  5.0
2018-07-18  3.0  4.0  5.0
2018-07-19  3.0  4.0  5.0

2

您使用的pandas版本是哪个版本? 从0.23.0版本开始,似乎可以在DataFrame中使用method:请参见文档


没错,我正在使用0.22.0版本。 - Florent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接