Python学习笔记(10):Pandas函数应用

今天来学习一下Pandas的两个主要数据结构,DataFrame和Series的函数应用。

1、numpy中的元素级方法都可以用于操作pandas对象

操作效果同numpy一样,会对数组中的所有元素进行操作,输出结果不会改变数组的行或列。

import pandas as pd
import numpy as np
from pandas import Series, DataFrame
frame = DataFrame(np.random.randn(4, 3), columns = list('bde'), index = ['Utah', 'Ohio', 'Texas', 'Oregon'])
frame
输出:
    b   d   e
Utah    -2.430792   0.114325    0.337033
Ohio    0.433084    -0.617763   1.334988
Texas   -0.044485   1.476422    1.647872
Oregon  -0.037739   0.295135    0.581948

np.abs(frame)
输出:
    b   d   e
Utah    2.430792    0.114325    0.337033
Ohio    0.433084    0.617763    1.334988
Texas   0.044485    1.476422    1.647872
Oregon  0.037739    0.295135    0.581948

好了,那么就可以顺便回顾一下Numpy中的元素级方法都有哪些。
Python学习笔记(3):Numpy基础之数组函数与数组数据处理

numpy中的元素级函数(一元函数)

2、apply()方法,将函数应用到DataFrame行或列组成的一维数组上

这里的示例代码会突然看到一个lambda,这个先简单理解为一句话函数的写法就好了。
apply方法可以对DataFrame的行或列生效,通过参数axis传递需要生效的轴。

f = lambda x: x.max() - x.min()
frame.apply(f)
输出:
b    2.863875
d    2.094185
e    1.310839
dtype: float64

frame.apply(f, axis = 1)
Utah      2.767824
Ohio      1.952751
Texas     1.692357
Oregon    0.619687
dtype: float64

传给apply的函数除了可以返回标量值,还可以返回一组Series对象。

def f(x):
    return Series([x.min(), x.max()], index = ['min', 'max'])
frame.apply(f)
输出:
b   d   e
min -2.430792   -0.617763   0.337033
max 0.433084    1.476422    1.647872

frame.apply(f, axis = 1)
输出:
              min   max
Utah    -2.430792   0.337033
Ohio    -0.617763   1.334988
Texas   -0.044485   1.647872
Oregon  -0.037739   0.581948

3、applymap(), map(),分别对DataFrame和Series元素使用自定义的元素级方法

format = lambda x: '%.2f' % x
frame.applymap(format)
输出:
    b   d   e
Utah    -2.43   0.11    0.34
Ohio    0.43    -0.62   1.33
Texas   -0.04   1.48    1.65
Oregon  -0.04   0.30    0.58

frame['e'].map(format)
输出:
Utah      0.34
Ohio      1.33
Texas     1.65
Oregon    0.58
Name: e, dtype: object

ok,工作日不宜学习太多。。晚安。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容