我正在尝试填充数据集“日期”列中缺少的值
CODE City Date TAVG TMAX TMIN
CA003033890 Lethbridge 08-01-2020 -3.55 4.7 -11.8
CA003033890 Lethbridge 09-01-2020 -17.05 -11.5 -22.6
CA003033890 Lethbridge 10-01-2020 -13.7 -1.9 -25.5
CA003033890 Lethbridge 11-01-2020 -7.8 0.7 -16.3
CA003033890 Lethbridge 12-01-2020 -20.3 -16.3 -24.3
CA003033890 Lethbridge 13-01-2020 -24.6 -22.4 -26.8
CA003033890 Lethbridge 14-01-2020 -27 -23.7 -30.3
CA003033890 Lethbridge 15-01-2020 -29.55 -26.8 -32.3
CA003033890 Lethbridge 16-01-2020 -26.05 -23.2 -28.9
CA003033890 Lethbridge 17-01-2020 -23.45 -19.2 -27.7
对于上面的代码CA003033890
,请注意,从2020年1月1日到2020年7月1日的日期缺失,类似地,对于其他CODE
列,随机缺失Date
列值
这是我试过的代码
data.Date=pd.to_datetime(data.Date)
merge_df = data.set_index('Date').groupby('CODE').apply(lambda x : x.resample('D').max().ffill()).reset_index(level=1)
当我运行它时,它似乎一直在运行,后来返回了下面的错误
Traceback (most recent call last):
File "test.py", line 45, in <module>
data['Date'] = data.groupby('CODE')['Date'].apply(lambda d: d.reindex(pd.date_range(min(df1.Date),max(df1.Date),freq='D'))).drop('CODE', axis=1).reset_index('CODE').fillna(value=None)
File "C:\Python\Python38\lib\site-packages\pandas\core\series.py", line 4132, in drop
return super().drop(
File "C:\Python\Python38\lib\site-packages\pandas\core\generic.py", line 3923, in drop
axis_name = self._get_axis_name(axis)
File "C:\Python\Python38\lib\site-packages\pandas\core\generic.py", line 420, in _get_axis_name
raise ValueError(f"No axis named {axis} for object type {cls}")
ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'>
预期数据集(数据集中的NAN)
CODE City Date TAVG TMAX TMIN
CA003033890 Lethbridge 01-01-2020
CA003033890 Lethbridge 02-01-2020
CA003033890 Lethbridge 03-01-2020
CA003033890 Lethbridge 04-01-2020
CA003033890 Lethbridge 05-01-2020
CA003033890 Lethbridge 06-01-2020
CA003033890 Lethbridge 07-01-2020
CA003033890 Lethbridge 08-01-2020 -3.55 4.7 -11.8
CA003033890 Lethbridge 09-01-2020 -17.05 -11.5 -22.6
CA003033890 Lethbridge 10-01-2020 -13.7 -1.9 -25.5
还有,有没有更快的方法来实现这一点
您可以在每个组中创建一个多索引和
reindex
,然后reset_index
:A MWE:
相关问题 更多 >
编程相关推荐