Pandas 模块-操纵数据(6)-DataFrame 使用自定义函数

目录

6. DataFrame 使用自定义函数

6.1 操作整个 DataFrame 的函数:.pipe()

6.1.1 .pipe() 语法

6.1.2 .pipe() 范例

6.2 操作行或者列的函数:.apply()

6.2.1 .apply() 语法

6.2.2 .apply() 范例

6.3 操作作单一元素的函数:.applymap()

6.3.1 .applymap() 语法

6.3.2 .applymap() 范例


如果想要应用自定义的函数,或者把其他库中的函数应用到 Pandas.DataFrame 对象中,有以下三种方法:

  • 操作整个 DataFrame 的函数:pipe()
  • 操作行或者列的函数:apply()
  • 操作单一元素的函数:applymap()

6. DataFrame 使用自定义函数

先准备数据吧

import pandas as pd
dict_data={"a":list("abcdef"),"b":list("defghi"),"c":list("ghijkl")}
df=pd.DataFrame.from_dict(dict_data)
df

得到结果

6.1 操作整个 DataFrame 的函数:.pipe()

6.1.1 .pipe() 语法

语法结构:DataFrame.pipe(func, *args, **kwargs)

参数说明:

  • func:一个应用于Series/DataFrame的函数,*args, **kwargs都是应用于这个函数的参数
  • args:迭代的参数,可选,可以是元组类型,也可以是列表类型或者其他。
  • kwargs:映射的参数,可选,是一个包含关键字的字典。

返回值:返回值由 func 的返回值决定

请注意,使用.pipe()时候,默认不会修改 DataFrame 本身

Help on method pipe in module pandas.core.generic:

pipe(func, *args, **kwargs) method of pandas.core.frame.DataFrame instance
    Apply func(self, \*args, \*\*kwargs).
    
    Parameters
    ----------
    func : function
        Function to apply to the Series/DataFrame.
        ``args``, and ``kwargs`` are passed into ``func``.
        Alternatively a ``(callable, data_keyword)`` tuple where
        ``data_keyword`` is a string indicating the keyword of
        ``callable`` that expects the Series/DataFrame.
    args : iterable, optional
        Positional arguments passed into ``func``.
    kwargs : mapping, optional
        A dictionary of keyword arguments passed into ``func``.
    
    Returns
    -------
    object : the return type of ``func``.
    
    See Also
    --------
    DataFrame.apply : Apply a function along input axis of DataFrame.
    DataFrame.applymap : Apply a function elementwise on a whole DataFrame.
    Series.map : Apply a mapping correspondence on a
        :class:`~pandas.Series`.
    
    Notes
    -----
    Use ``.pipe`` when chaining together functions that expect
    Series, DataFrames or GroupBy objects. Instead of writing

6.1.2 .pipe() 范例

.pipe()的用法非常简单,先看个代码就明白了

def f(dataframe,*args,**kwargs):
    for tmpar
  • 0
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江南野栀子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值