[英]Transform from 2-level MultiIndex to 3-level MultiIndex
我有以下數據結構的東西:
foo year
par chi
10.0 900 0.024096 1983
901 0.200000 1983
902 0.300000 1983
900 0.027473 1984
901 0.023256 1984
902 0.400000 1984
900 0.018182 1985
也就是說,對於每個父子/年組合,我對foo
都有一些觀察。 現在,對於每個父級,我想計算每個chi
與每個chi
(在此數據集900和901中)之間的協方差,即隨着時間的推移, chi_1
和chi_2
的foo
項隨時間變化,給定的par
?)。
我認為“最簡單”的方法是第二次將chi
作為第三級索引引入數據集中,但是我得到的只是:
index = pd.MultiIndex.from_product([par, chi, chi])
其中par
, chi
是索引的唯一值。 但是,我找不到一種對練習有用的方法來重新索引我的數據。 我將如何進行呢?
解決方案:
par
組,應用一個計算子協方差的函數 year
,每個孩子的foo
值在單獨的列中 chi
和chi_other
組合獲得一行。 例:
df = pd.DataFrame({'chi': [900, 901, 902, 900, 901, 902, 900],
'foo': [0.024096, 0.2, 0.3, 0.027473, 0.023256, 0.4, 0.018182],
'par': [10, 10, 10, 10, 10, 10, 10],
'year': [1983, 1983, 1983, 1984, 1984, 1984, 1985]})
def child_covariances(group):
x = group.set_index(['year','chi'])['foo'].unstack()
x = pd.melt(x.cov().reset_index(), id_vars=['chi'],
var_name='chi_other', value_name='foo_cov')\
.set_index(['chi','chi_other'])\
.query('chi <= chi_other').sort_index()
return x
res = df.groupby('par').apply(child_covariances)
# foo_cov
# par chi chi_other
# 10 900 900 0.000022
# 901 -0.000298
# 902 0.000169
# 901 901 0.015619
# 902 -0.008837
# 902 902 0.005000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.