【发布时间】:2021-07-15 10:32:52
【问题描述】:
我正在尝试从多个 csv 文件中插入多个时间序列的位置数据。我已经能够读取 csv 文件并将它们保存到每个时间序列的数据帧字典中。
我现在正在寻找插入这些时间序列。我已经尝试过代码攻击,但出现以下错误:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
Python 代码:
import glob
path = r'C:\Users\drifters' # use your path
all_files = glob.glob(path + "/*.csv")
drifters = {}
for idx, filename in enumerate(all_files,start=1):
drifters["drifter{0}".format(idx)] = pd.read_csv(filename, index_col=None, header=0, parse_dates={"date_time": ['Date', 'Time']})
drifters_interp = {}
for idx, (key,value) in enumerate(drifters.items(),start=1):
drifters_interp["drifter{0}".format(idx)] = drifters[key].set_index('date_time').resample('2min').mean().interpolate('linear')
有没有办法遍历一个字典、插值并保存到另一个字典?
编辑:
这是完整的错误:
文件“”,第 12 行,在 drifters_interp["drifter{0}".format(idx)] =drifters[key].set_index('date_time').resample('2min').mean().interpolate('linear')
文件“C:\Users\nkj19blc\Anaconda3\lib\site-packages\pandas\core\generic.py”,第 8096 行,重新采样 偏移量=偏移量,
文件“C:\Users\nkj19blc\Anaconda3\lib\site-packages\pandas\core\resample.py”,第 1270 行,在 get_resampler return tg._get_resampler(obj, kind=kind)
文件“C:\Users\nkj19blc\Anaconda3\lib\site-packages\pandas\core\resample.py”,第 1436 行,在 _get_resampler "仅对 DatetimeIndex 有效,"
TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了 'Index' 的实例
看一下漂流者字典:
查看其中一个 DataFrame:
【问题讨论】:
-
哪一行引发异常?我们可以得到完整的例外吗?
-
快速提示:当您在解决错误时遇到困难,使用函数式编程,尝试将失败的调用放在自己的线路上。 1. 你可能会发现你错误的来源是错误的 2. 它使得在失败代码之前和之后打印/记录变得容易,从而使调试变得容易。
-
@FlorianFasmeyer 谢谢 - 我已经上传了完整的错误。
-
该错误是由
resample引发的,而不是由interpolate引发的。set_index似乎返回了您没想到的东西。注意:感谢您的编辑! -
你能告诉我们你的
'date_time'专栏吗?
标签: python pandas for-loop interpolation