pandas DataFrame 计算每周协方差

huangapple go评论52阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2023年3月20日 23:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定