如果想要应用自定义的函数,或者把其他库中的函数应用到 Pandas.DataFrame 对象中,有以下三种方法:
- 操作整个 DataFrame 的函数:pipe()
- 操作行或者列的函数:apply()
- 操作单一元素的函数:applymap()
DataFrame 使用自定义函数
import pandas as pd
dict_data={"a":list("abcdef"),"b":list("defghi"),"c":list("ghijkl")}
df=pd.DataFrame.from_dict(dict_data)
df
得到结果
操作整个 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 tmparg in args:
dataframe+="-"+str(tmparg)
for tmpkey,tmpvalue in kwargs