【问题标题】:Find and Add Missing Column Values Based on Index Increment Python Pandas Dataframe基于索引增量 Python Pandas Dataframe 查找和添加缺失的列值
【发布时间】:2021-05-07 03:41:15
【问题描述】:

下午好!

我有一个带有索引和计数的 pandas 数据框。

dictionary = {1:5,2:10,4:3,5:2}
df = pd.DataFrame.from_dict(dictionary , orient = 'index' , columns = ['count'])

我想要做的是从 df.index.min() 到 df.index.max() 检查索引增量是否为 1。如果缺少一个值,例如在我的情况下缺少 3,那么我想将 3 添加到索引中,计数为 0。

输出将类似于下面的 df2,但以编程方式完成,因此我可以在更大的数据帧上使用它。

结果示例 DF:

dictionary2 = {1:5,2:10,3:0,4:3,5:2}
df2 = pd.DataFrame.from_dict(dictionary2 , orient = 'index' , columns = ['count'])

非常感谢!!!

【问题讨论】:

    标签: python-3.x pandas dataframe indexing


    【解决方案1】:

    确保索引已排序:

    df = df.sort_index()
    

    创建一个从最小索引开始到最大索引的数组

       complete_array = np.arange(df.index.min(), df.index.max() + 1)
    

    重新索引,用 0 填充空值,并可选择将 dtype 更改为 Pandas Int:

    df.reindex(complete_array, fill_value=0).astype("Int16")
    
        count
    1   5
    2   10
    3   0
    4   3
    5   2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 2016-10-06
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      相关资源
      最近更新 更多