重采样熊猫数据帧时出现类型错误

时间:2021-05-11 08:46:05

标签: python pandas dataframe

我想在 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()

我将原始数据帧中的列时间转换为日期时间,否则熊猫会将其视为对象类型(如此处推荐的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):

您可以在此处看到数据框的屏幕截图Screenshot

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

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

1 个答案:

答案 0 :(得分:1)

总结我们的谈话:

  • 这一行 new = df_generation_short['Biomass'].resample('1H').mean() 抛出了类型错误:
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()