【问题标题】:TypeError when resampling a pandas dataframe重新采样熊猫数据框时出现类型错误
【发布时间】:2021-05-11 08:46:05
【问题描述】:

我想在 Pandas 数据框中每隔 4 行重新采样一次。正如建议How to select every 4th row in a pandas dataframe and calculate the rolling average这里我使用以下代码

import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow import keras
from matplotlib import pyplot as plt



#Read the input data
df_generation = pd.read_csv("C:/Users/Data/Electricity Price Forecasting/Generation.csv", sep =";")
print(df_generation.dtypes)
df_generation_short = df_generation[0:2000]
df_generation_short['Time'] = pd.to_datetime(df_generation_short['Time'])

new = df_generation_short['Biomass'].resample('1H').mean()

我将原始数据框中的列时间转换为日期时间,因为否则 pandas 将其视为对象类型(此处推荐 enter link description here 但是,我仍然收到错误消息

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

在错误告诉我之前我也会收到警告:

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  df_generation_short['Time'] = pd.to_datetime(df_generation_short['Time'])
Traceback (most recent call last):

这里可以看到dataframe的截图

您知道我为什么会收到此错误以及如何解决此问题吗?我会很感激每一条评论。

更新:我根据一条评论的建议进行了尝试,并使用了 apply 功能: df_generation_short.apply(pd.to_datetime(df_generation_short['Time'])) 但我收到错误消息“ValueError:无结果”。有没有人知道如何解决这个问题?不知何故,pandas 不接受“时间”列作为带有索引的日期对象,尽管我使用 df_generation_short['Time'] = pd.to_datetime(df_generation_short['Time']) 对其进行了转换。

【问题讨论】:

  • 你应该对你的对象apply使用函数df_generation_short
  • 感谢 dallonsi 的评论。我应该在哪里以及如何使用 apply?
  • @dallonsi:我试过df_generation_short.apply(pd.to_datetime(df_generation_short['Time'])),但收到错误消息“ValueError: no results”
  • 关于你的SettingWithCopyWarning:我建议你阅读这篇文章:stackoverflow.com/a/53954986/4909087
  • 非常感谢 dallonsi 的回答和努力。对此,我真的非常感激。是的,这实际上解决了问题。非常感谢您的巨大帮助(如果您在答案中写下此内容,我会赞成并接受它,以便您获得积分)。

标签: python pandas dataframe


【解决方案1】:

总结我们的谈话:

  • new = df_generation_short['Biomass'].resample('1H').mean() 这一行会抛出 TypeError:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
  • 这是因为Biomass 列不包含日期输入。因此,为了解决这个问题,请将 DataFrame 索引设置为列Time
df_generation_short = df_generation_short.set_index('Time')
  • 现在,如果您想在 1 小时的窗口内获取 Biomass 的平均值,
new = df_generation_short['Biomass'].resample('1H').mean()
  • 此外,如果您想计算所有列的平均值,只需省略指定列
new = df_generation_short.resample('1H').mean()

或者,如果您希望它用于两个特定列:例如“生物质”和“化石油”:

new = df_generation_short[["Biomass", "Fossil Oil"]].resample('1H').mean()

【讨论】:

  • 感谢您的回答 dallonsi。基本上我遇到了一个问题。在使用 df_generation_short = df_generation[0:2000] 创建的缩短数据帧上应用您建议的代码时,它可以完美运行。但是在整个数据帧上使用它时,我得到了错误TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'。知道为什么会这样吗?
  • 此代码使用短数据框工作:df_generation = pd.read_csv("C:/Users/Data/Electricity Price Forecasting/Generation.csv", sep =";") df_generation['Time'] = pd.to_datetime(df_generation['Time']) df_generation = df_generation.set_index('Time') df_generation_short = df_generation[0:2000] new_shortDataframe = df_generation_short['Biomass'].resample('1H').mean()
  • 虽然此代码使用整个数据框导致上述 TyperError:df_generation = pd.read_csv("C:/Users/Data/Electricity Price Forecasting/Generation.csv", sep =";") df_generation['Time'] = pd.to_datetime(df_generation['Time']) df_generation = df_generation.set_index('Time') new_wholeDataframe = df_generation['Biomass'].resample('1H').mean()
  • 好的,在整个 DataFrame 上(即不要使用:df_generation_short = df_generation[0:2000]),pd.to_datetime(df_generation_short['Time']) 行会抛出错误吗?这可能是因为您的 DataFrame 包含“坏”条目
  • 感谢 dallonsi 的回答和建议。基本上我弄清楚了问题是什么,但我仍然需要考虑如何解决它。问题是夏季/冬季时间的变化。因此,特定时间的时间值存在两次,而其他时间不存在任何值。但这可能是另一个问题。我要感谢您的巨大帮助和努力。对此,我真的非常感激。我赞成并接受了你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 2016-10-18
  • 2021-06-17
  • 2020-01-10
  • 2017-02-14
  • 2020-11-18
  • 2017-03-19
相关资源
最近更新 更多