【问题标题】:Pandas add NA rows based on indexPandas 根据索引添加 NA 行
【发布时间】:2015-11-15 01:32:50
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

            Product_1  Product_2  Product_3  Product_4  Product_5
1492        1944         NaN         NaN         NaN         NaN         
1493        1944         NaN         NaN       16482        6185         
1494        1944       13208       20378       16482        6185         
1498        2146       13208       20378       16482        6694        
1503        2146       13973       20378       16552        6694

我希望在所有列中输入带有 NaN 值的新行 1495、1496、1497 以及类似的 1499、1500、1501 和 1502。这似乎是一个非常简单的工作,只是想知道是否有内置的 pandas 函数可以做这样的事情。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用.reindex:

    >>> df.reindex(range(1492, 1504))
          Product_1  Product_2  Product_3  Product_4  Product_5
    1492       1944        NaN        NaN        NaN        NaN
    1493       1944        NaN        NaN      16482       6185
    1494       1944      13208      20378      16482       6185
    1495        NaN        NaN        NaN        NaN        NaN
    1496        NaN        NaN        NaN        NaN        NaN
    1497        NaN        NaN        NaN        NaN        NaN
    1498       2146      13208      20378      16482       6694
    1499        NaN        NaN        NaN        NaN        NaN
    1500        NaN        NaN        NaN        NaN        NaN
    1501        NaN        NaN        NaN        NaN        NaN
    1502        NaN        NaN        NaN        NaN        NaN
    1503       2146      13973      20378      16552       6694
    

    【讨论】:

    • 哦,该死的,为什么我在文档中找不到这种方法,现在听起来像一个愚蠢的问题。不过还是谢谢。
    • 而不是硬编码,可能是相对值df.reindex(range(min(df.index), max(df.index)))
    • @PierreLafortune 应该是df.index.max() + 1,因为range 不包括右端
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 2016-06-01
    • 1970-01-01
    相关资源
    最近更新 更多