博客
关于我
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 pandas库详解_Pandas 库的详解和使用补充
查看>>
Python Pandas滚动聚合一列列表
查看>>
python pandas相关知识点(练习)
查看>>
Python Pandas,从.groupby().Apply()中的GROUP中分割行
查看>>
Python pathlib模块详解:优雅处理文件路径
查看>>
python Path模块的使用 glob iglob name
查看>>
python pickle 模块的使用
查看>>
Python PIL/Pillow-Pad图像至所需大小(例如,A4)
查看>>
python PIL模框使用
查看>>
Python ping 模块
查看>>
Python Pingouin:搞定各种假设检验和统计模型 !
查看>>
Python pip 国内镜像大全及使用办法
查看>>
Python输入输出练习,运算练习,turtle初步练习
查看>>
Python pip工具使用
查看>>
Python pip配置国内源
查看>>
Python Plotly 将轴数格式化为 %
查看>>
Redis 键值过期操作
查看>>
python predictabel_基于R语言PredictABEL包对Logistic回归模型外部验证
查看>>
Python psycopg2 超时
查看>>
Python Pyinstaller Matplotlibrary
查看>>