繁体   English   中英

基于缺失列名切割pandas DataFrame时出错

[英]Error in slicing pandas DataFrame based on Missing column names

我有一个带有多个索引和列的pandas数据框我想根据一些列名对这个数据帧进行切片,但有时候给定的列名不在数据帧中。 Pandas提出警告使用.reindex而不是.loc但是我发现了奇怪的结果。 为了澄清,让我们加载dataFrame

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)

我按照警告的建议尝试使用reindex,如本帖所示,但结果是没有!!

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的列):

indicators_list = ['ind475', 'ind179']
print (df2.loc[:, df2.columns.isin(indicators_list)])

要么:

print (df2[df2.columns[df2.columns.isin(indicators_list)]])

如果使用get_level_values ,请使用get_level_values

print (df2.loc[:, df2.columns.get_level_values(0).isin(indicators_list)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM