英文:
pandas daframe compute covarince weekly
问题
我有这个数据框:
np.random.seed(0)
start_d = '2018-01-01 00:00:00'
start_d = pd.to_datetime(start_d,format='%Y-%m-%d %H:%M:%S')
end_d = '2018-01-28 00:00:00'
end_d = pd.to_datetime(end_d,format='%Y-%m-%d %H:%M:%S')
index = pd.date_range(start = start_d, end = end_d)
df = pd.DataFrame(index=index,data=np.random.randint(0,100,size=(28, 2)), columns=list('AB'))
我想计算两个序列之间的相关性,但基于每周。换句话说,我考虑一种特定应用的重新采样。我的想法是同时应用Pearson和Spearman。为了表达清楚:
df.resample('W').corr(method='spearman)
你觉得呢?能做类似的事情吗?
祝好。
英文:
I have this dataframe
np.random.seed(0)
start_d = '2018-01-01 00:00:00'
start_d = pd.to_datetime(start_d,format='%Y-%m-%d %H:%M:%S')
end_d = '2018-01-28 00:00:00'
end_d = pd.to_datetime(end_d,format='%Y-%m-%d %H:%M:%S')
index = pd.date_range(start = start_d, end = end_d)
df = pd.DataFrame(index=index,data=np.random.randint(0,100,size=(28, 2)), columns=list('AB'))
I would like to compute the correlation between the two series but on a weekly base. In other words, I am thinking about a sort of resample with a specific apply. My idea is to apply both Pearson and Spearman. To make myself clear:
df.resample('W').corr(method='spearman)
What do you think? Is it possible to do something similar?
Best.
答案1
得分: 1
如果我理解这个问题正确,你试图在每周的水平上获得相关性。是否有多年的日期?
如果只有一年:
# 设置周数:
df['Week_Number'] = df['Date'].dt.isocalendar().week
# 现在按周数分组,并获得相关性:
df.groupby('Week_Number')[['A', 'B']].corr()
如果有超过1年:
# 设置周数和年份:
df['Week_Number'] = df['Date'].dt.isocalendar().week
df['Year'] = df['Date'].dt.year
# 现在按周数和年份分组,并获得相关性:
df.groupby(['Week_Number', 'Year'])[['A', 'B']].corr()
英文:
If I understand this question correctly, you're trying to get the correlation at a week level. Are there multiple years of dates?
If you only have one year:
# Set the week number:
df['Week_Number'] = df['Date'].dt.isocalendar().week
# Now groupby the week number, and get the correlation:
df.groupby('Week_Number')[['A', 'B']].corr()
If you have >1 year:
# Set both the week and year:
df['Week_Number'] = df['Date'].dt.isocalendar().week
df['Year'] = df['Date'].dt.year
# Now groupby the week number and year, and get the correlation:
df.groupby(['Week_Number', 'Year'])[['A', 'B']].corr()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论