pandas:apply(),applymap(),map()
自己總結一下:
1.apply()
Series.apply:For applying more complex functions on a Series。
對Series的值調用函數??梢允莡func(一個適用于整個系列的NumPy函數)還是一個只對單個值有效的Python函數。
>>> series = pd.Series([20, 21, 12], index=['London', ... 'New York','Helsinki']) >>> series London 20 New York 21 Helsinki 12 dtype: int64>>> def square(x): ... return x**2 >>> series.apply(square) London 400 New York 441 Helsinki 144 dtype: int64>>> series.apply(lambda x: x**2) London 400 New York 441 Helsinki 144 dtype: int64DataFrame.apply:Apply a function row-/column-wise,按行/列方式應用函數
沿著DataFrame的輸入軸應用函數
>>> df.apply(numpy.sqrt) # returns DataFrame >>> df.apply(numpy.sum, axis=0) # equiv to df.sum(0) #作用的列上,可以省略 >>> df.apply(numpy.sum, axis=1) # equiv to df.sum(1) #作用在行上2.applymap()
DataFrame.applymap:Apply a function elementwise on a whole DataFrame
在整個DataFrame上應用函數
>>> df = pd.DataFrame(np.random.randn(3, 3)) >>> df0 1 2 0 -0.029638 1.081563 1.280300 1 0.647747 0.831136 -1.549481 2 0.513416 -0.884417 0.195343 >>> df = df.applymap(lambda x: '%.2f' % x) >>> df0 1 2 0 -0.03 1.08 1.28 1 0.65 0.83 -1.55 2 0.51 -0.88 0.203.map():
Series.map(arg,?na_action=None):Map values of Series using input correspondence (which can be a dict, Series, or function)
map()只要是作用將函數作用于一個Series的每一個元素,用法如下所示?
擴充:
DataFrame.aggregate(agg):only perform aggregating type operations,只執行聚合類型操作
DataFrame.transform:only perform transformating type operations,只執行轉換類型操作
加載數據
- 可以看到數據包含了不同的訂單(order),以及訂單里的不同商品的數量(quantity)、單價(unit price)和總價(ext price)
- 現在我們的任務是為數據表添加一列,表示不同商品在所在訂單的價錢占比。
- 首先我們要獲得每個訂單的總花費。groupby可以實現。
?
?
- 這些新得到的數據如何與原始數據幀結合呢? order_total = df.groupby('order')["ext price"].sum().rename("Order_Total").reset_index()df_1 = df.merge(order_total) df_1["Percent_of_Order"] = df_1["ext price"] / df_1["Order_Total"]
?
- 我們實現了目標(還多加了一列訂單總額),但是步驟比較多,有沒有更好的辦法呢?——主角出場:)
?tramsform:
df.groupby('order')["ext price"].transform('sum')0 576.12 1 576.12 2 576.12 3 8185.49 4 8185.49 5 8185.49 6 8185.49 7 8185.49 8 3724.49 9 3724.49 10 3724.49 11 3724.49 dtype: float64?
- 不再是只顯示3個訂單的對應項,而是保持了與原始數據集相同數量的項目,這樣就很好繼續了。這就是transform的獨特之處。
甚至可以一步:?
df["Percent_of_Order"] = df["ext price"] / df.groupby('order')["extprice"].transform('sum')?
參考:https://www.jianshu.com/p/509d7b97088c
總結
以上是生活随笔為你收集整理的pandas:apply(),applymap(),map()的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习变量转换(定性变量、定量变量)
- 下一篇: python:copy()和deepco