博客
关于我
python_链式编程技术_管道技术
阅读量:386 次
发布时间:2019-03-05

本文共 1004 字,大约阅读时间需要 3 分钟。

链式编程技术与管道技术

在处理数据集时,经常会发现多次变换后产生的临时变量实际上并未在分析中使用。例如:

df = load_data()df2 = df[df['col2'] < 0]df2['col1_demeaned'] = df2['col1'] - df2['col1'].mean()result = df2.groupby('key').col1_demeaned.std()

虽然这段代码没有使用真实数据,但它揭示了一些新的方法。首先,DataFrame.assign 是一种类似 df[k] = v 的函数式方法,可以用来对 DataFrame 进行列赋值。它的使用方式是返回修改后的新 DataFrame,而不是在原 DataFrame 上进行修改。因此,以下两种写法是等价的:

# 常规非函数式写法df2 = df.copy()df2['k'] = v# 函数式写法df2 = df.assign(k=v)

在链式编程中,需要注意临时对象的使用。例如:

df = load_data()result = (df          .pipe(f, arg1=v1)          .pipe(g, v2, arg3=v3)          .pipe(h, arg4=v4))

df.pipe(f)f(df) 是等价的,但 pipe 方法使链式编程更加便捷。此外,pipe 也可以接受类似函数的参数,即可调用的对象(callable),这对于复用操作非常有用。

在处理分组数据时,以下方法可以有效地将操作转换为可复用的函数:

def group_demean(df, by, cols):    result = df.copy()    g = df.groupby(by)    for c in cols:        result[c] = df[c] - g[c].transform('mean')    return result

可以通过以下方式使用:

result = (df          .pipe(group_demean, ['key1', 'key2'], ['col1'])          .groupby('key')          .col1_demeaned.std())

通过这种方式,链式编程使得数据转换更加灵活和可读。

转载地址:http://fnrg.baihongyu.com/

你可能感兴趣的文章
python | feature_engine,一个实用的 Python 库!
查看>>
python | filelock,一个超酷的 Python 库!
查看>>
python | fire,一个强大的 Python 库!
查看>>
python | flanker,一个神奇的 Python 库!
查看>>
python | flower,一个强大的 Python 库!
查看>>
python | funcy,一个超强的 提供函数式编程工具 Python 库!
查看>>
python | ggplot,一个超强的 Python 库!
查看>>
python | grab,一个强大的 Python 库!
查看>>
python | gunicorn,一个非常实用的 Python 库!
查看>>
python | h5py,一个无敌的关于 HDF5 的 Python 库!
查看>>
python | huey,一个非常厉害的 任务调度 Python 库!
查看>>
python | hypothesis,一个有趣的 Python 库!
查看>>
python | Indico,一个超酷的 Python 库!
查看>>
python | isort,一个有趣的 自动整理导入语句 的Python 库!
查看>>
python | jinja,一个超酷的 Python 库!
查看>>
python | joblib,一个强大的 Python 库!
查看>>
python调用git bash_Python学习第70课-用Git Bash在命令行打开sublime
查看>>
python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
查看>>
python课程的中期报告范文_课题研究中期总结报告范文
查看>>
python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
查看>>