【问题标题】:Different fill methods for different columns in pandaspandas中不同列的不同填充方法
【发布时间】:2013-10-30 23:53:33
【问题描述】:

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

df.reindex(newIndex,method='ffill')

但我意识到我需要逐列以不同方式处理缺失数据。也就是说,对于某些列,我想填充,但对于其他列,我想丢失记录为 NA 的值。

为简单起见,假设我有想要填充的 X 列和想要 NA 填充的 Y 列。如何调用 .reindex 来完成此操作?

【问题讨论】:

  • 不能调用两次吗?使用columns=[Y] 参数和columns=[X] 参数?
  • @jaor 所以你的意思是做两个单独的索引,然后合并两个结果数据帧?
  • 我猜。参数columns 仅影响指定的列。都在这里我猜pandas.pydata.org/pandas-docs/stable/generated/…
  • reindex,然后根据需要在各个列上添加fillna

标签: python pandas


【解决方案1】:

您可以先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

输出:

    A    B    C
2   10  100  100
4   10  100  NaN
6   20  200  200
8   30  300  300
10  30  300  NaN

【讨论】:

    猜你喜欢
    • 2022-11-30
    • 2014-08-17
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多