Python 使用pandas在具有重复日期的csv文件中添加缺少的日期
我有一个数据集,它有134列和11961行。它有重复的日期,因为事件持续了2天。所以它被记录为三行。 因此,当我试图通过此链接添加缺少的日期时。但我犯了个错误Python 使用pandas在具有重复日期的csv文件中添加缺少的日期,python,pandas,csv,Python,Pandas,Csv,我有一个数据集,它有134列和11961行。它有重复的日期,因为事件持续了2天。所以它被记录为三行。 因此,当我试图通过此链接添加缺少的日期时。但我犯了个错误 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") Va
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
方法1:使用重采样
注意:这将删除重复的行
方法2:使用
pd.concat
,布尔索引
,重采样
是否要保留重复项,如
1979-8-27
行?或者我们可以删除副本吗?我希望副本存在。但也展示了如何删除重复项你看了我的答案了吗?它提供了这两个…我现在验证了。。。。它的工作。。。非常感谢,事实上我犯了个错误。但后来我忘了写点什么。现在它可以完美地工作了,我应该如何删除重复的行并将重复的数据与单行(唯一的行)合并
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
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