首页 > 解决方案 > 如何使用已准备好列/列参数列表的功能扩展熊猫?

问题描述

有一个不错的库 pandas-flavor https://pypi.org/project/pandas-flavor/允许扩展 pandas。

我写了这样的玩具示例:

import pandas as pd
import pandas_flavor as pf
from scipy import stats


df = pd.DataFrame(data={
  "x": ['a', 'a', 'b'],
  "y": [0, 2, 5],
  "z": [5, 0, 7],
})


@pf.register_dataframe_method
def to_frame(df):
  return df

@pf.register_dataframe_method
def custom_func(df, grouping, c):
  return df.groupby(grouping)[c].transform(stats.zscore).to_frame().max(axis=1)

基本上,c参数现在可以是单个列(字符串)或custom_func(主要目标)的列列表:

df.custom_func(['x'], 'y')
df.custom_func(['x'], ['y'])
df.custom_func(['x'], ['y', 'z'])

几点说明:

它有效,但问题是:

标签: pythonpandaspandas-groupbycustomization

解决方案


推荐阅读