pandas数据帧中降低列级别的方法链接解决方案

2024-06-16 14:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在重塑和查询pandasDataFrames中的数据时,我使用了大量的方法链接。有时会为索引(行)和列创建额外的和不必要的级别。如果是这样,例如在索引(行轴)上,这很容易通过使用DataFrame.reset_index()来解决:

df.query('some query')
   .apply(cool_func)
   .reset_index('unwanted_index_level',drop=True) # <====
   .apply(another_cool_func)

reset_index函数允许继续使用链式方法并继续使用DataFrame。在

然而,我从来没有找到一个与列轴相等的解决方案。有没有?在


Tags: 数据方法dataframedfindex链接级别query
3条回答

我自己刚刚找到了另一个解决方案,即使用DataFrame.T字段,它相当于DataFrame.transpose()。在

df.query('some query')
   .apply(cool_func)
   .T.reset_index('unwanted_col_level_name',drop=True).T
   .apply(another_cool_func)

允许连续点链接的一个选项是为pd.DataFrame类定义一个新方法,该方法可以降低列索引级别。这叫做monkey patching,它降低了代码的可移植性。在

def reset_column_index(self, inplace=False):
    if inplace:
        self.columns = ['_'.join(tup) for tup in self.columns]
    else:
        c = self.copy()
        c.columns = ['_'.join(tup) for tup in c.columns]
        return c

pd.DataFrame.reset_column_index = reset_column_index

df.query('some query')
   .apply(cool_func)
   .reset_column_index()
   .apply(another_cool_func)

使用此方法可以将多索引列展平为单个索引,并使用下划线合并名称。在

^{pr2}$

变成

#   foo_A   foo_B   bar_A   bar_B
# 0    17       2       0       3
# 1     4      12      40      11

您只需stack列(将其移动到索引)并使用drop=True调用reset_index,或者可以使用reset_index()作为起点编写reset_columns()方法(请参见框架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)

替代方案:猴头贴解决方案

^{pr2}$

相关问题 更多 >