python - ffill 不在 pandas dataframe 中填充数据

标签 python pandas dataframe nan

我有一个这样的数据框:

  A  B  C  E D
---------------
0 a  r  g    g
1            x
2 x  f  f    r
3            t
3            y

我正在尝试使用 ffill 进行正向填充。它不工作

 cols = df.columns[:4].tolist()
 df[cols] = df[cols].ffill()

我也试过:

df[cols] = df[cols].fillna(method='ffill')

但是它没有被填满。 是数据中的空列导致了这个问题吗?

数据被模拟。确切数据不同(包含字符串、数字和空列)

期望的职业:

  A  B  C  E D
---------------
0 a  r  g    g
1 a  r  g    x
2 x  f  f    r
3 x  f  f    t
3 x  f  f    y

最佳答案

NaN 替换列子集中的空值:

df[cols] = df[cols].replace('', np.nan).ffill()

关于python - ffill 不在 pandas dataframe 中填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51278897/

相关文章:

python - Many-Hot(N-hot)编码 - 快速 Pandas 方法?

python - 如何找到IronPython的安装路径

python - 在 Python 中打印 subprocess.Popen() 输出

python - 将字符串中的单词替换为 pandas 数据框中的单词

python - 使用逻辑填充缺失数据 Pandas

python - 如何更改满足特定条件的数据框中的第一个值

r - 将 R 数据框中特定列的文本大写

python - 在 numpy 中按索引选择

python - 如何订购sqlite操作

python - Pandas - 返回日期范围的单个日期并匹配工作日二进制值