[英]Pandas: Select from date in MultiIndex
假設我有MultiIndex系列
date foo
2006-01-01 1 12931926.310
3 11084049.460
5 10812205.359
7 9031510.239
9 5324054.903
2007-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
如果不是MultiIndex,則可以通過df.loc['2007']
選擇年份為2007
df.loc['2007']
。 我在這里怎么做? 我的自然猜測是df.loc['2007', :]
,但這給了我一個空的Series([], name: FINLWT21, dtype: float64)
。
Ultimatively,我也有興趣在替換所有行的不同的日期比2007
同一年中的行2007
。
也就是說,我的預期輸出是
date foo
2006-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
2007-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
我試圖實現@unutbu的解決方案,但是
mySeries.loc[dateIndex.year != 2007] = mySeries.loc[dateIndex.year == 2007]
會自然地將值(由於RHS上不存在)設置為NaN
。 通常,這些問題是通過以下方式解決的
mySeries.loc[dateIndex.year != 2007] = mySeries.loc[dateIndex.year == 2007].values
,但假設我的左側有10
值(在我的實際數據集中還有更多),而右側只有5
,
ValueError: cannot set using a list-like indexer with a different length than the value
我現在想到的唯一選擇是遍歷第一個索引,然后對每個子組使用上一個命令,但這似乎不是最有效的解決方案。
給定系列
In [207]: series
Out[212]:
date foo
2006-01-01 1 12931926.310
3 11084049.460
5 10812205.359
7 9031510.239
9 5324054.903
2007-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
Name: val, dtype: float64
您可以使用提取date
索引
dateindex = series.index.get_level_values('date')
# Ensure the dateindex is a DatetimeIndex (as opposed to a plain Index)
dateindex = pd.DatetimeIndex(dateindex)
現在可以使用布爾條件選擇年份等於2007的行:
# select rows where year equals 2007
series2007 = series.loc[dateindex.year == 2007]
如果foo
值在每個日期中以相同的順序循環顯示相同的值,那么您可以將序列中的所有值替換為2007年的值,
N = len(series)/len(series2007)
series[:] = np.tile(series.loc[dateindex.year == 2007].values, N)
使用np.tile
和.values
一個優點是它將相對快速地生成所需的值數組。 一個(可能的)缺點是,它忽略了索引,因此它依賴於以下假設:對於每個日期, foo
值以相同的順序循環通過相同的值。
更健壯(但更慢)的方法是使用聯接:
df = series.reset_index('date')
df2007 = df.loc[dateindex.year==2007]
df = df.join(df2007, rsuffix='_2007')
df = df[['date', 'val_2007']]
df = df.set_index(['date'], append=True)
df = df.swaplevel(0,1).sort_index()
產量
In [304]: df.swaplevel(0,1).sort_index()
Out[304]:
val_2007
date foo
2006-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
2007-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
2008-01-01 1 11086082.624
3 12028419.560
5 11957253.031
7 10643307.061
9 6034854.915
要從MultiIndex中選擇所需年份(例如2007)的值,可以使用:
target_year = 2007
df[[ts.year == target_year for ts in df.index.get_level_values(0)]]
如果日期索引不是時間戳的形式,則需要進行轉換:
df[[pd.Timestamp(ts).year == target_year for ts in df.index.get_level_values(0)]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.