1.DataFrame的常用函数: (1)np.abs(frame) 绝对值, (2)apply function, lambda f= lambda x: x.max()-x.min(),frame.apply(f); frame.apply(f,axis = 1) f(x), def f(x): return Series([x.min(),x.max()], index=[‘min‘,‘max‘]),frame.apply(f)(3) applymap format f= lambda x:‘%.2f‘ %x, frame.applymap(f) 或者 frame[‘e‘].map(format)
2. index 或者 column的排序 ‘‘‘function application and mapping‘‘‘import numpy as npfrom pandas import DataFrame , Seriesframe = DataFrame(np.random.randn(4, 3), columns=list(‘bde‘), index=[‘Utah‘, ‘Ohio‘, ‘Texas‘, ‘Oregon‘])print("frame is \n", frame)print("np.abs(frame) is \n", np.abs(frame))print("another frequent operation is applying a function on 1D arrays to each column or row.\n DataFrame‘s apply method does exactly this:")f = lambda x: x.max()-x.min()print("f = lambda x: x.max()-x.min()")print("frame.apply(f):", frame.apply(f))print("frame.apply(f,axis=1):",frame.apply(f,axis=1))def f(x): return Series([x.min(), x.max()], index=[‘min‘, ‘max‘])print("frame.apply(f): \n", frame.apply(f))print("the function pass to apply need not to return a scalar value,it can also return a series with multiple values") format = lambda x: ‘%.2f‘ % xprint("frame.applymap(format): \n", frame.applymap(format))print("frame[‘e‘].map(format): \n", frame[‘e‘].map(format))
obj = Series(range(4),index=[‘d‘, ‘a‘, ‘b‘, ‘c‘])print("obj.sort_index: \n", obj.sort_index()) frame = DataFrame(np.arange(8).reshape((2, 4)), index=[‘three‘, ‘one‘], columns= [‘d‘, ‘a‘, ‘b‘, ‘c‘])print("frame is \n", frame)print("frame.sort_index() \n", frame.sort_index())print("frame.sort_index(axis=1) \n", frame.sort_index(axis=1)) print("frame.sort_index(axis=1,ascending=False): \n", frame.sort_index(axis=1,ascending=False))
时间: 2024-10-27 09:05:49