【问题标题】:How to interpolate a series of python dataframes in one dictionary and save to another?如何在一个字典中插入一系列 python 数据帧并保存到另一个?
【发布时间】: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


【解决方案1】:

调用set_index后,尝试将DataFrame的索引变成DatetimeIndex

data.index = pd.to_datetime(data.index, unit='s')

如果这可行,那么您可能需要确保您提供给set_index 的列确实是pandas.Datetime 类型。使用 DataFrame.dtypes 检查您的 DataFrame。

【讨论】:

  • 你是对的。由于某些时间序列具有 NaN,因此对于某些数据帧,整列没有转换为日期时间。我通过将第二个 for 循环编辑为以下内容来解决它:for idx, (key,value) in enumerate(drifters.items(),start=1): drifter_df = drifters[key].dropna() drifter_df['date_time'] = pd.to_datetime(drifter_df['date_time']) drifters_interp["drifter{0}".format(idx)] = drifter_df.set_index('date_time').resample('2min').mean().interpolate('linear') 谢谢你的帮助。
猜你喜欢
  • 2021-04-09
  • 1970-01-01
  • 2021-05-08
  • 2017-05-18
  • 1970-01-01
  • 2021-11-06
  • 2011-07-25
  • 1970-01-01
  • 2021-04-26
相关资源
最近更新 更多