def adder(ele1,ele2): return ele1+ele2然后使用自定义的函数对 DataFrame 进行操作:
df = pd.DataFrame(np.random.randn(4,3),columns=['c1','c2','c3']) #传入自定义函数以及要相加的数值3 df.pipe(adder,3)完整的程序,如下所示:
import pandas as pd import numpy as np #自定义函数 def adder(ele1,ele2): return ele1+ele2 #操作DataFrame df = pd.DataFrame(np.random.randn(4,3),columns=['c1','c2','c3']) #相加前 print(df) #相加后 print(df.pipe(adder,3))输出结果:
c1 c2 c3 0 1.989075 0.932426 -0.523568 1 -1.736317 0.703575 -0.819940 2 0.657279 -0.872929 0.040841 3 0.441424 1.170723 -0.629618 c1 c2 c3 0 4.989075 3.932426 2.476432 1 1.263683 3.703575 2.180060 2 3.657279 2.127071 3.040841 3 3.441424 4.170723 2.370382
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) df.apply(np.mean) #默认按列操作,计算每一列均值 print(df.apply(np.mean))输出结果:
col1 0.277214 col2 0.716651 col3 -0.250487 dtype: float64传递轴参 axis=1, 表示逐行进行操作,示例如下:
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df) print (df.apply(np.mean,axis=1))输出结果:
col1 col2 col3 0 0.210370 -0.662840 -0.281454 1 -0.875735 0.531935 -0.283924 2 1.036009 -0.958771 -1.048961 3 -1.266042 -0.257666 0.403416 4 0.496041 -1.071545 1.432817 0 -0.244641 1 -0.209242 2 -0.323908 3 -0.373431 4 0.285771 dtype: float64求每一列中,最大值与最小值之差。示例如下:
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df.apply(lambda x: x.max() - x.min()))输出结果:
col1 3.538252 col2 2.904771 col3 2.650892 dtype: float64
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) #自定义函数lambda函数 print(df['col1'].map(lambda x:x*100))输出结果:
0 -18.171706 1 1.582861 2 22.398156 3 32.395690 4 -133.143543 Name: col1, dtype: float64下面示例使用了 applymap() 函数,如下所示:
import pandas as pd import numpy as np #自定义函数 df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df.applymap(lambda x:x*10)) print(df.apply(np.mean))输出结果:
col1 col2 col3 0 -1.055926 7.952690 15.225932 1 9.362457 -12.230732 7.663450 2 2.910049 -2.782934 2.073905 3 -12.008132 -1.444989 5.988144 4 2.877850 6.563894 8.192513 #求均值: col1 0.041726 col2 -0.038841 col3 0.782879 dtype: float64
本文链接:http://task.lmcjl.com/news/17256.html