【问题标题】:Pad middle values based on previouse and next values根据上一个和下一个值填充中间值
【发布时间】:2023-02-14 23:05:22
【问题描述】:

假设我 df 像这样

   col     col2
0    0  Repeat1
1    3  Repeat2
2    5  Repeat3
3    7  Repeat4
4    9  Repeat5

可重现

L= [0,3,5,7,9]
L2 = ['Repeat1','Repeat2','Repeat3','Repeat4','Repeat5']

import pandas as pd
df = pd.DataFrame({'col':L})
df['col2']= L2
print (df)

如何填充缺失的中间值,使我的 df 看起来像这样

  col     col2
0    0  Repeat1
1    1  Repeat1
2    2  Repeat1
3    3  Repeat2
4    4  Repeat2
5    5  Repeat3
6    6  Repeat3
7    7  Repeat4
8    8  Repeat4
9    9  Repeat5

我试过的类似线程

Filling missing middle values in pandas dataframe(为中间值填充 Nan 值,但我不需要 Nan)

Fill pandas dataframe with values in between(非常大的方法。我正在寻找任何功能性方法)

这两种情况都在一定程度上帮助了我但我想知道有什么办法吗? :D

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用“col”作为临时索引的 reindexffill

    out = (df.set_index('col')
             .reindex(range(df['col'].max()+1))
             .ffill()
             .reset_index()
          )
    

    输出:

       col     col2
    0    0  Repeat1
    1    1  Repeat1
    2    2  Repeat1
    3    3  Repeat2
    4    4  Repeat2
    5    5  Repeat3
    6    6  Repeat3
    7    7  Repeat4
    8    8  Repeat4
    9    9  Repeat5
    

    【讨论】:

    • 谢谢@mozway ..如果我的列有重复值怎么办?我不能使用这个如果我有重复的值它会抛出ValueError: cannot reindex on an axis with duplicate labels
    • @Bhargav 那么预期的行为是什么?你能提供另一个例子吗? (几乎)一切皆有可能,但你必须明确定义规则;)
    • 不好意思更新...
    • 我正在弄清楚自己@mozway ..如果我自己弄不明白,我会伸出援手.. :D
    【解决方案2】:

    你也可以mergeffill

    (df.merge(pd.DataFrame({'col': range(df['col'].max()+1)}), how='right')
           .ffill()
        )
    

    输出:

       col     col2
    0    0  Repeat1
    1    1  Repeat1
    2    2  Repeat1
    3    3  Repeat2
    4    4  Repeat2
    5    5  Repeat3
    6    6  Repeat3
    7    7  Repeat4
    8    8  Repeat4
    9    9  Repeat5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多