Method chaining solution to drop column level in pandas DataFrame(Pandas DataFrame中删除列级的方法链接解决方案)
                            本文介绍了Pandas DataFrame中删除列级的方法链接解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我在重塑和查询我在 pandas DataFrames中的数据时使用的是Lot of方法链。有时会为in索引(行)和列创建额外的和不必要的级别。如果是,例如在索引(行轴)上,可以使用DataFrame.reset_index():
df.query('some query')
   .apply(cool_func)
   .reset_index('unwanted_index_level',drop=True) # <====
   .apply(another_cool_func)
reset_index函数允许用户继续链接方法并继续使用DataFrame。
尽管如此,我从来没有为Column_Axis找到一个等价的解决方案。有吗?
推荐答案
您可以只调用stack列(将其移动到索引中),并使用Drop=True调用reset_index,或者您可以使用reset_index()作为起点编写reset_columns()方法(请参阅Frame.py#L2940)
df.query('some query')
   .apply(cool_func)
   .stack(level='unwanted_col_level_name')
   .reset_index('unwanted_col_level_name',drop=True)
   .apply(another_cool_func)
替代方案:猴贴溶液
def drop_column_levels(self, level=None, inplace=False):
        """
        For DataFrame with multi-level columns, drops one or more levels.
        For a standard index, or if dropping all levels of the MultiIndex, will revert
        back to using a classic RangeIndexer for column names.
        Parameters
        ----------
        level : int, str, tuple, or list, default None
            Only remove the given levels from the index. Removes all levels by
            default
        inplace : boolean, default False
            Modify the DataFrame in place (do not create a new object)
        Returns
        -------
        resetted : DataFrame
        """
        if inplace:
            new_obj = self
        else:
            new_obj = self.copy()
        new_columns = pd.core.common._default_index(len(new_obj.columns))
        if isinstance(self.index, pd.MultiIndex):
            if level is not None:
                if not isinstance(level, (tuple, list)):
                    level = [level]
                level = [self.index._get_level_number(lev) for lev in level]
                if len(level) < len(self.columns.levels):
                    new_columns = self.columns.droplevel(level)
        new_obj.columns = new_columns
        if not inplace:
            return new_obj
# Monkey patch the DataFrame class
pd.DataFrame.drop_column_levels = drop_column_levels
这篇关于Pandas DataFrame中删除列级的方法链接解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:Pandas DataFrame中删除列级的方法链接解决方案
 
				
         
 
            
        基础教程推荐
             猜你喜欢
        
	     - 当按下按钮时,将动态创建的按钮信息传递给函 2022-09-21
- 在VBA中调用python代码:权限错误 2022-09-22
- H5py:如何在HDF5组和数据集上使用key()循环 2022-09-21
- 多索引数据帧删除每个组具有最大值的行 2022-09-22
- 使用Python访问已在运行的进程 2022-09-21
- IBM Watson SpechtoTextV1错误-Python 2022-09-22
- Socket.recv为空,但结果显示在Maya中 2022-09-21
- 跟在带量词的前瞻后面有什么作用? 2022-09-22
- GridSearchCV.Best_Score不同于CROSS_VAL_Score(GridSearchCV. 2022-09-21
- 使用pyinstaller后,Python应用程序无法运行,但未显 2022-09-21
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				