【发布时间】: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):
您知道我为什么会收到此错误以及如何解决此问题吗?我会很感激每一条评论。
更新:我根据一条评论的建议进行了尝试,并使用了 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 的回答和努力。对此,我真的非常感激。是的,这实际上解决了问题。非常感谢您的巨大帮助(如果您在答案中写下此内容,我会赞成并接受它,以便您获得积分)。