python - 如何使用已准备好列/列参数列表的功能扩展熊猫?
问题描述
有一个不错的库 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'])
几点说明:
- 对于单列
df.groupby(grouping)[c].transform(stats.zscore)
返回Series
,它max(axis=1)
会给出错误,除非你把它变成DataFrame
(to_frame()
) - 对于多个列
df.groupby(grouping)[c].transform(stats.zscore)
给出DataFrame
但没有to_frame()
它,所以我通过 pandas-flavor 添加了它
它有效,但问题是:
- 可以更简单或更标准的方式完成吗?
- 是否有标准方法来编写可用于单列/多列的函数?
解决方案
推荐阅读
- vue.js - 如何在使用 jest 测试 vuetify 组件时解决“SyntaxError: Unexpected identifier”
- python - 用于聚合和可视化数据的交互式应用程序:pandas+绘图库是正确的工具吗?
- r - 使用 RWeka 创建朴素贝叶斯分类器时遇到问题
- angular - 当路由存在时,为什么我从 Express Route 收到 404 错误?
- javascript - Vue prop 在对计算函数的初始调用中未定义
- sql - SQL 中 GROUP BY 后的 Tableau 计数值
- ms-access - 如何在使用模板的 word doc 中创建下拉列表?
- ios - 奇怪的行为设置 tableView 行高和 scrollPosition Swift
- node.js - 如何添加“原因”来禁止命令
- sql - 使用存储过程将查询结果插入表时出现问题