【问题标题】:I need to insert null values for missing index in python pandas我需要为 python pandas 中的缺失索引插入空值
【发布时间】:2018-10-02 08:13:33
【问题描述】:

我有一个数据集

x  text
1  one
2  two
4  four
5  five
7  seven

现在我想输出为

x  text
1  one
2  two
3  null
4  four
5  five
6  null
7  seven

【问题讨论】:

    标签: python pandas missing-data


    【解决方案1】:

    使用reindex:

    #if x is column
    #df = df.set_index('x').reindex(np.arange(df.index.min(), df.index.max() + 1))
    #if x is index
    df = df.reindex(np.arange(df.index.min(), df.index.max() + 1))
    print (df)
        text
    x       
    1    one
    2    two
    3    NaN
    4   four
    5   five
    6    NaN
    7  seven
    

    【讨论】:

    • 我试过了,但我收到了这个错误 ->AttributeError: 'Series' object has no attribute 'set_index'
    • @RahulVarma - 使用第二个答案 - df = df.reindex(np.arange(df.index.min(), df.index.max() + 1))
    • @RahulVarma - print(df.index) 是什么?
    猜你喜欢
    • 2015-06-10
    • 2019-06-24
    • 2016-10-06
    • 1970-01-01
    • 2019-05-04
    • 2013-07-31
    • 2018-10-12
    • 2015-12-13
    相关资源
    最近更新 更多