Lesson7——Pandas 使用自定义函数
简介
如果想要应用自定义的函数,或者把其他库中的函数应用到 Pandas 对象中,有以下三种方法:
- 操作整个 DataFrame 的函数:pipe()
- 操作行或者列的函数:apply()
- 操作单一元素的函数:applymap()
下面介绍了三种方法的使用。
1 操作整个数据表
通过给 pipe() 函数传递一个自定义函数和适当数量的参数值,从而操作 DataFrme 中的所有元素。
下面示例,实现了数据表中的元素值依次加 3。
df = pd.DataFrame(np.arange(6).reshape(2,3),columns=['col1','col2','col3'])
#相加前
print(df)
#相加后
print(df.pipe(add,3))
输出结果:
col1 col2 col3
0 0 1 2
1 3 4 5
col1 col2 col3
0 3 4 5
1 6 7 8
2 操作行或列
如果要操作 DataFrame 的某一行或者某一列,可以使用 apply() 方法,该方法与描述性统计方法类似,都有可选参数 axis,并且默认按列操作。示例如下:
df2 =pd.DataFrame(data=np.arange(6,12).reshape((-1,3)),columns=['col1','col2','col3'],index=[2,3])
df = df.append(df2)
df
输出结果:
col1 col2 col3
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
继续:
df.apply(np.mean)
输出结果:
col1 4.5
col2 5.5
col3 6.5
dtype: float64
示例:
df.apply(np.mean,axis =1)
输出结果:
0 1.0
1 4.0
2 7.0
3 10.0
dtype: float64
求每一列中,最大值与最小值之差。示例如下:
print(df.apply(lambda x: x.max() - x.min()))
输出结果:
col1 9
col2 9
col3 9
dtype: int64
3 操作单一元素
DataFrame 数据表结构的 applymap() 和 Series 系列结构的 map() 类似,它们都可以接受一个 Python 函数,并返回相应的值。
示例如下:
df = pd.DataFrame(np.arange(6).reshape((-1,3)),columns=['col1','col2','col3'])
print(df)
#自定义函数lambda函数
print(df['col1'].map(lambda x:x*2))
输出结果:
col1 col2 col3
0 0 1 2
1 3 4 5
0 0
1 6
Name: col1, dtype: int64
下面示例使用了 applymap() 函数,如下所示:
#自定义函数
df = pd.DataFrame(np.arange(6).reshape((-1,3)),columns=['col1','col2','col3'])
print(df.applymap(lambda x:x*2))
print(df.apply(np.mean))
输出结果:
col1 col2 col3
0 0 2 4
1 6 8 10
col1 1.5
col2 2.5
col3 3.5
dtype: float64
因上求缘,果上努力~~~~ 作者:多发Paper哈,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/15866516.html