我有一个包含多个索引和列的熊猫数据帧我想根据某些列名对这个数据帧进行切片,但有时给定的列名不在数据帧中。熊猫发出警告,使用.reindex
而不是.loc
但我发现了奇怪的结果。为了澄清,让我们加载数据帧
import pandas as pd
d2 = pd.read_csv('https://docs.google.com/uc?id=1Ufx6pvnSC6zQdTAj05ObmV027fA4-Mr3&export=download', index_col=[0,1])
d2.head(3)
结果是:
..............................................
: : : ind475 : ind476 : ind456 :
:..........:......:........:........:........:
: Country : Year : : : :
: Argentin : 1966 : 6.15 : 7.77 : NaN :
: : 1967 : 8.33 : 9.81 : NaN :
: : 1968 : 9.19 : 10.2 : NaN :
:..........:......:........:........:........:
如果我们使用现有列进行切片,那么没问题:
indicators_list = ['ind475', 'ind456']
idx = pd.IndexSlice
d3 = d2.loc[idx[:,:], idx[indicators_list]]
d3.dropna(axis=0, how='all').dropna(axis=1, how='all').shape
出>> (10006,2(
但是,如果我们使用一个或多个缺失的列进行切片,则会引发错误,但它有效
indicators_list = ['ind475', 'ind179']
d4 = d2.loc[idx[:,:], idx[indicators_list]]
d4.dropna(axis=0, how='all').dropna(axis=1, how='all').shape
出>> (2672, 1(带有红色警告
FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike
return self._getitem_nested_tuple(tup)
我尝试按照警告的建议和这篇文章中所示使用重新索引,但结果是没有!!
indicators_list = ['ind475', 'ind179']
d5 = d2.reindex(columns=[indicators_list])
d5.dropna(axis=0, how='all').dropna(axis=1, how='all').shape
出:>> (0, 0(
如何在没有警告或错误的情况下切片并获得适当的大小?
我相信
您需要使用isin
过滤列名称(然后在必要时删除NaN
s列(:
indicators_list = ['ind475', 'ind179']
print (df2.loc[:, df2.columns.isin(indicators_list)])
或:
print (df2[df2.columns[df2.columns.isin(indicators_list)]])
如果使用多索引,请使用get_level_values
:
print (df2.loc[:, df2.columns.get_level_values(0).isin(indicators_list)])