【发布时间】:2021-08-11 04:13:11
【问题描述】:
我一直在尝试创建一个通用的天气导入器,它可以重新采样数据以设置间隔(例如,从 20 分钟到几小时等(我在下面的代码中使用了 60 分钟))。 为此,我想使用 Pandas 重采样功能。经过一番困惑后,我想出了下面的代码(这不是最漂亮的代码)。我在设定时间段内平均风向时遇到了一个问题,我试图用 pandas 的 resampler.apply 来解决这个问题。
但是,我遇到了一个定义问题,它给出了以下 错误: TypeError: can't convert complex to float
我意识到我正在尝试将方形钉钉在圆孔中,但我不知道如何克服这一点。任何提示将不胜感激。
import pandas as pd
import os
from datetime import datetime
from pandas import ExcelWriter
from math import *
os.chdir('C:\\test')
file = 'bom.csv'
df = pd.read_csv(file,skiprows=0, low_memory=False)
#custom dataframe reampler (.resampler.apply)
def custom_resampler(thetalist):
try:
s=0
c=0
n=0.0
for theta in thetalist:
s=s+sin(radians(theta))
c=c+cos(radians(theta))
n+=1
s=s/n
c=c/n
eps=(1-(s**2+c**2))**0.5
sigma=asin(eps)*(1+(2.0/3.0**0.5-1)*eps**3)
except ZeroDivisionError:
sigma=0
return degrees(sigma)
# create time index and format dataframes
df['DateTime'] = pd.to_datetime(df['DateTime'],format='%d/%m/%Y %H:%M')
df.index = df['DateTime']
df = df.drop(['Year','Month', 'Date', 'Hour', 'Minutes','DateTime'], axis=1)
dfws = df
dfwdd = df
dfws = dfws.drop(['WDD'], axis=1)
dfwdd = dfwdd.drop(['WS'], axis=1)
#resample data to xxmin and merge data
dfwdd = dfwdd.resample('60T').apply(custom_resampler)
dfws = dfws.resample('60T').mean()
dfoutput = pd.merge(dfws, dfwdd, right_index=True, left_index=True)
# write series to Excel
writer = pd.ExcelWriter('bom_out.xlsx', engine='openpyxl')
dfoutput.to_excel(writer, sheet_name='bom_out')
writer.save()
【问题讨论】:
-
可以试试 pandas Grouper 吗? pandas.Grouper
-
嗨@IbraheemAyoup,感谢您的评论。不幸的是,grouper 不能用于此,因为我无法对其应用定义来计算循环平均值。我遇到的问题更多地与定义有关。再次感谢您的意见
标签: python pandas circular-dependency