Python中pandas函数应用!
Pandas 可直接使用 NumPy 的 ufunc(元素级数组方法) 函数:
>>> import pandas as pd >>> import numpy as np >>> obj = pd.DataFrame(np.random.randn(5,4) - 1) >>> obj 0 1 2 3 0 -0.228107 1.377709 -1.096528 -2.051001 1 -2.477144 -0.500013 -0.040695 -0.267452 2 -0.485999 -1.232930 -0.390701 -1.947984 3 -0.839161 -0.702802 -1.756359 -1.873149 4 0.853121 -1.540105 0.621614 -0.583360 >>> >>> np.abs(obj) 0 1 2 3 0 0.228107 1.377709 1.096528 2.051001 1 2.477144 0.500013 0.040695 0.267452 2 0.485999 1.232930 0.390701 1.947984 3 0.839161 0.702802 1.756359 1.873149 4 0.853121 1.540105 0.621614 0.583360
函数映射:在 Pandas 中 apply 方法可以将函数应用到列或行上,可以通过设置 axis 参数来指定行或列,默认 axis = 0,即按列映射:
>>> import pandas as pd >>> import numpy as np >>> obj = pd.DataFrame(np.random.randn(5,4) - 1) >>> obj 0 1 2 3 0 -0.707028 -0.755552 -2.196480 -0.529676 1 -0.772668 0.127485 -2.015699 -0.283654 2 0.248200 -1.940189 -1.068028 -1.751737 3 -0.872904 -0.465371 -1.327951 -2.883160 4 -0.092664 0.258351 -1.010747 -2.313039 >>> >>> obj.apply(lambda x : x.max()) 0 0.248200 1 0.258351 2 -1.010747 3 -0.283654 dtype: float64 >>> >>> obj.apply(lambda x : x.max(), axis=1) 0 -0.529676 1 0.127485 2 0.248200 3 -0.465371 4 0.258351 dtype: float64
另外还可以通过 applymap 将函数映射到每个数据上:
>>> import pandas as pd >>> import numpy as np >>> obj = pd.DataFrame(np.random.randn(5,4) - 1) >>> obj 0 1 2 3 0 -0.772463 -1.597008 -3.196100 -1.948486 1 -1.765108 -1.646421 -0.687175 -0.401782 2 0.275699 -3.115184 -1.429063 -1.075610 3 -0.251734 -0.448399 -3.077677 -0.294674 4 -1.495896 -1.689729 -0.560376 -1.808794 >>> >>> obj.applymap(lambda x : '%.2f' % x) 0 1 2 3 0 -0.77 -1.60 -3.20 -1.95 1 -1.77 -1.65 -0.69 -0.40 2 0.28 -3.12 -1.43 -1.08 3 -0.25 -0.45 -3.08 -0.29 4 -1.50 -1.69 -0.56 -1.81
Python更多知识,请关注云海天Python教程!!
来源:PY学习网:原文地址:https://www.py.cn/article.html