python - 使用熊猫在具有重复日期的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
解决方案
方法一:使用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
推荐阅读
- javascript - how integrate a scroll-down effect with velocity.js in a react application without jquery?
- mongodb - Connecting Android Studio with MongoDB
- html - 如何将此 div 标签放在框的右侧?
- c++ - ffmpeg mpg 转 jpg
- python - 使用非 ascii 字符从 csv 文件中删除 null
- hyperledger-fabric - 第一个网络示例:调用期间的背书失败
- laravel - 在 laravel 数据库中上传后在浏览器中显示图像文件
- c# - C# Discord bot 获取发件人头像
- scala - Spark Streaming 标准示例中缺少所需的配置“bootstrap.servers”错误
- sql - 从没有任何格式的日期中提取时间