为什么在使用DataFrame.rename之后不能使用DataFrame [DataFrame.ColumnA == somevalue]?

问题描述

我有如下数据,


In [20]: test_data
Out[22]: 
                    ut  first_name_ini
0  WOS:000386321800001     Enriquez,F
1  WOS:000386321800001      Troyano,J
2  WOS:000386321800001  Lopez-Solaz,T
3  WOS:000386321800002    da Rochaa,S
4  WOS:000386321800002  Braz Junior,G

然后对“ first_name_ini”列中的元素进行计数,并获得包含两列“ index”和“ irst_name_ini”的DataFrame(group_index)

In [23]: test_data.first_name_ini.value_counts().reset_index()
Out[23]: 
            index  first_name_ini
0      Troyano,J               1
1  Braz Junior,G               1
2    da Rochaa,S               1
3  Lopez-Solaz,T               1
4     Enriquez,F               1

重命名列名后,过滤数据时出现错误

group_index = test_data.first_name_ini.value_counts().reset_index() 
group_index.rename(columns={'index':'name','first_name_ini':'count'},inplace=True)
In [24]: group_index[group_index.count == 50]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
d:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self,key,method,tolerance)
   3077             try:
-> 3078                 return self._engine.get_loc(key)
   3079             except KeyError:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: False

During handling of the above exception,another exception occurred:

KeyError                                  Traceback (most recent call last)
<ipython-input-24-f9c9f110b694> in <module>()
----> 1 group_index[group_index.count == 50]

d:\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self,key)
   2686             return self._getitem_multilevel(key)
   2687         else:
-> 2688             return self._getitem_column(key)
   2689 
   2690     def _getitem_column(self,key):

d:\Anaconda3\lib\site-packages\pandas\core\frame.py in _getitem_column(self,key)
   2693         # get column
   2694         if self.columns.is_unique:
-> 2695             return self._get_item_cache(key)
   2696 
   2697         # duplicate columns & possible reduce dimensionality

d:\Anaconda3\lib\site-packages\pandas\core\generic.py in _get_item_cache(self,item)
   2487         res = cache.get(item)
   2488         if res is None:
-> 2489             values = self._data.get(item)
   2490             res = self._Box_item_values(item,values)
   2491             cache[item] = res

d:\Anaconda3\lib\site-packages\pandas\core\internals.py in get(self,item,fastpath)
   4113 
   4114             if not isna(item):
-> 4115                 loc = self.items.get_loc(item)
   4116             else:
   4117                 indexer = np.arange(len(self.items))[isna(self.items)]

d:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self,tolerance)
   3078                 return self._engine.get_loc(key)
   3079             except KeyError:
-> 3080                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   3081 
   3082         indexer = self.get_indexer([key],method=method,tolerance=tolerance)

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: False

但是当更改下面的代码时,它可以工作

In [25]: group_index[group_index['count'] == 50]
Out[25]: 
                 name  count
2723           Dey,N     50
2724           Tan,Q     50
2725        Bazzan,A     50
2726           Fan,K     50
2727         Botti,V     50
2728      Atkinson,K     50

那么DataFrame[DataFrame.ColumnA == somevalue]DataFrame[DataFrame['ColumnA'] == somevalue]间的区别是什么,从group_index[group_index['count'] == 50]group_index[group_index.count == 50],为什么在DataFrame.rename()之后出现错误

解决方法

问题是因为您要引用的列countpandas.DataFrame.count方法冲突,所以无法进行此属性样式的访问。鼓励在过滤时始终使用显式词典样式的group_index['count'] == 50

,

group_index.countgroup_index['count']之间的主要区别在于,第一个被称为对象的属性,而第二个被称为对象的索引。如果count列事先不存在,则不能将其作为属性调用,因为尚未设置该属性,因此python不会知道您要指的是什么。但是,如果您使用索引将其设置为某种值(例如使用group_index['count']的情况),大熊猫会在幕后创建新属性,并在您使用group_index['count']类似于在像dct['count'] = some_value这样的python字典中设置新键时的操作(请注意,这并不是完美的比较,因为您无法直接将python dict键作为属性来调用,但是概念相似)。

这有点涉及面向对象的编程,如果仍然感到困惑,应该研究一下。如果您仍然对上面的代码有麻烦,我相信只需放下inplace部分就可以解决问题,因为熊猫会处理该操作并在设置对新框架的引用之前创建所需的任何属性。>

group_index = group_index.rename(columns={'index':'name','first_name_ini':'count'})