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

时间:2018-07-26 10:00:02

标签: python pandas numpy dataframe

我有一个包含多个列的数据框,我想一次用列中的上一个值将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 个答案:

答案 0 :(得分:2)

可能是这样:

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

答案 1 :(得分:2)

您使用哪个版本的熊猫? 似乎他们在0.23.0版的DataFrame中增加了使用方法的可能性:请参见docs