将自定义或其他库的函数应用于Pandas对象,包括三个重要的方法,下面来讨论如何使用这些方法。 使用适当的方法取决于函数是否期望在整个DataFrame的行或列或元素上进行操作。
- 表合理函数应用:
pipe()
- 行或列函数应用:
apply()
- 元素函数应用:
applymap()
def adder(ele1,ele2):
return ele1+ele2
现在将使用自定义函数对DataFrame进行操作。
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.pipe(adder,2)
下面来看看完整的程序:
import pandas as pd
import numpy as np
def adder(ele1,ele2):
return ele1+ele2
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.pipe(adder,2)
print(df)
col1 col2 col3 0 0.101374 1.817888 0.508670 1 0.397177 -1.240096 1.088969 2 -0.551540 0.201353 0.287811 3 0.868320 -0.699200 -0.069302 4 -1.014809 -0.965152 -0.081125
示例-1
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.apply(np.mean)
print(df)
col1 col2 col3 0 -0.087287 1.098061 -0.609207 1 -0.420798 -0.825102 -0.057582 2 0.422160 -1.708893 -0.476010 3 0.639554 -0.240102 -1.357671 4 -0.071007 -1.328412 1.704068
通过传递 axis
参数,可以在行上执行操作。
示例-2
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.apply(np.mean,axis=1)
df
col1 | col2 | col3 | |
---|---|---|---|
0 | -0.286720 | 0.808633 | -0.049787 |
1 | 0.283086 | -1.458874 | -0.510850 |
2 | -0.093904 | 0.652910 | -1.161362 |
3 | -0.942456 | -1.057818 | 0.312184 |
4 | 0.630112 | -0.998350 | 0.499817 |
示例-3
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.apply(lambda x: x.max() - x.min())
df
col1 | col2 | col3 | |
---|---|---|---|
0 | -0.285233 | 0.540603 | 0.231059 |
1 | 1.411677 | -1.204034 | -0.647869 |
2 | 0.092699 | 0.692457 | 0.037930 |
3 | -0.772451 | -0.915245 | -0.625946 |
4 | 0.308487 | 0.642400 | -1.268724 |
示例-1
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
我的自定义函数
df['col1'].map(lambda x:x*100)
df
col1 | col2 | col3 | |
---|---|---|---|
0 | 0.825033 | -0.538591 | 1.581332 |
1 | -0.876872 | -0.096785 | 1.101833 |
2 | 0.748241 | -0.835690 | 0.610582 |
3 | 0.897007 | -0.240702 | 0.143898 |
4 | -0.482668 | 2.282380 | -0.712711 |
示例-2
我的自定义函数
df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3'])
df.applymap(lambda x:x*100)
df
/tmp/ipykernel_4569/4216040453.py:2: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead. df.applymap(lambda x:x*100)
col1 | col2 | col3 | |
---|---|---|---|
0 | -0.724915 | -1.148476 | -2.099224 |
1 | 0.533404 | -0.363225 | 0.829124 |
2 | 0.342817 | 0.792029 | 1.235701 |
3 | 0.890871 | -0.646763 | 1.627931 |
4 | -0.048208 | 0.097819 | -0.029209 |