pandas中不同列的不同填充方法

mou*_*hio 2 python pandas

我正在以标准方式重新索引数据帧,即

df.reindex(newIndex,method='ffill')
Run Code Online (Sandbox Code Playgroud)

但意识到我需要逐列处理丢失的数据.也就是说,对于某些我希望填充的列,但对于其他列,我希望丢失记录为NA的值.

为简单起见,假设我想要填充的X列,以及我希望NA填充的Y列.我如何调用.reindex来完成此任务?

HYR*_*YRY 6

您可以reindex()先,然后调用ffill()列:

import pandas as pd
df = pd.DataFrame({"A":[10, 20, 30], "B":[100, 200, 300], 
                   "C":[100, 200, 300]}, index=[2, 6, 8])
df2 = df.reindex([2,4,6,8,10])

for col in ["A", "B"]:
    df2[col].ffill(inplace=True)
print df2
Run Code Online (Sandbox Code Playgroud)

输出:

    A    B    C
2   10  100  100
4   10  100  NaN
6   20  200  200
8   30  300  300
10  30  300  NaN
Run Code Online (Sandbox Code Playgroud)