首页 > 解决方案 > 使用熊猫在具有重复日期的csv文件中添加缺少的日期

问题描述

我有一个数据集,它有 134 列和 11961 行。它有重复的日期,因为活动持续了 2 天。所以它被记录为三个不同的行。因此,当我尝试借助此链接添加缺少的日期时,请在 dataframe 中添加缺少的日期索引。但我遇到了一个错误。

File "C:\Users\kumar\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3576, in _can_reindex
    raise ValueError("cannot reindex from a duplicate axis")

ValueError: cannot reindex from a duplicate axis

原始数据是

    date  provstate  city  latitude  longitude
    1979-8-26   13  1850    22.804567   86.202875
    1979-8-27   7   3312    28.585836   77.153336
    1979-8-27   7   3312    28.585836   77.153336
    1979-8-29   13  1850    22.804567   86.202875

我使用的代码是这个

    df = pd.read_csv("G:\\Required\\Internship\\Fresh\\temp.csv", index_col='date')
    df.head()
    df.index = pd.DatetimeIndex(df.index)
    df = df.reindex(pd.date_range("1979-01-01", "2017-12-31"), fill_value=0)
    df.to_csv('test.csv')

我希望输出是

    date    provstate   city    latitude    longitude
    1979-8-26   13  1850    22.804567   86.202875
    1979-8-27   7   3312    28.585836   77.153336
    1979-8-27   7   3312    28.585836   77.153336
    1979-8-28   0   0       0           0
    1979-8-29   13  1850    22.804567   86.202875

但实际上我得到了错误

File "C:\Users\kumar\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 3576, in _can_reindex
    raise ValueError("cannot reindex from a duplicate axis")

ValueError: cannot reindex from a duplicate axis

标签: pythonpandascsv

解决方案


方法一:使用resample

注意:这会删除重复的行

df.resample('D').first().fillna(0)

            provstate    city   latitude  longitude
date                                               
1979-08-26       13.0  1850.0  22.804567  86.202875
1979-08-27        7.0  3312.0  28.585836  77.153336
1979-08-28        0.0     0.0   0.000000   0.000000
1979-08-29       13.0  1850.0  22.804567  86.202875

方法 2:使用pd.concat, boolean indexing&resample

d = df.resample('D').first().fillna(0)

df = pd.concat([df, d[~d.index.isin(df.index)]]).sort_index()

            provstate    city   latitude  longitude
date                                               
1979-08-26       13.0  1850.0  22.804567  86.202875
1979-08-27        7.0  3312.0  28.585836  77.153336
1979-08-27        7.0  3312.0  28.585836  77.153336
1979-08-28        0.0     0.0   0.000000   0.000000
1979-08-29       13.0  1850.0  22.804567  86.202875

推荐阅读