我有一个包含两级多索引行的数据框。类型为<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/google_places_api_key" />
和<class 'pandas.tseries.index.DatetimeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
我试图获得所有行,其中contract_serial = 201410&#39;例如。
我尝试了 px_settlement contract_code
assessment_date contract_serial
2014-01-02 201402 18.640 g14
201403 17.530 h14
201404 16.600 j14
201405 15.900 k14
201406 16.100 m14
201407 16.200 n14
201408 15.210 q14
201409 15.210 u14
201410 15.210 v14
201411 15.210 x14
.loc
也
jkm_df.loc[:, 201506]
TypeError: cannot do label indexing on <class 'pandas.indexes.base.Index'> with these indexers [201506] of <class 'int'>
通过assessment_date或contract_serial选择此多重索引的正确方法是什么?
答案 0 :(得分:2)
print (jkm_df.xs(201406, level=1))
px_settlement contract_code
assessment_date
2014-01-02 16.1 m14
如果必要,两个级别都使用参数drop_level=False
:
print (jkm_df.xs(201406, level=1, drop_level=False))
px_settlement contract_code
assessment_date contract_serial
2014-01-02 201406 16.1 m14
DataFrame.xs
的解决方案:
print (jkm_df.loc(axis=0)[:, 201406])
px_settlement contract_code
assessment_date contract_serial
2014-01-02 201406 16.1 m14
loc
的另一个解决方案:
print (jkm_df.loc[(slice(None), 201406), :])
px_settlement contract_code
assessment_date contract_serial
2014-01-02 201406 16.1 m14
答案 1 :(得分:2)
xs
适用于检索标量值。另一种解决方案(提供更多灵活性)是使用pd.IndexSlice
+ loc
。
idx = pd.IndexSlice
df.loc[idx[:, 201410], :]
px_settlement contract_code
assessment_date contract_serial
2014-01-02 201406 16.1 m14