編寫一個Python程式,生成一個包含30個元素的隨機陣列(元素值從1到100),並計算資料框中每一行的最大值與最小值的比值。


生成資料框每一行最大值與最小值比值的結果是

0    43.000000
1    1.911111
2    2.405405
3    20.000000
4    7.727273
5    6.333333

為了解決這個問題,我們將遵循以下步驟:

方案一

  • 定義一個包含30個從1到100的隨機元素的資料框,並將陣列重塑為(6,5)以轉換為二維陣列。

df = pd.DataFrame(np.random.randint(1,100,30).reshape(6,5))
  • 在lambda方法內建立df.apply函式來計算np.max(x)/np.min(x),其中axis為1,並將其儲存為max_of_min。其定義如下:

max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
  • 最後列印max_of_min

示例

讓我們檢查下面的程式碼來更好地理解:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(1,100,30).reshape(6,5))
print("Dataframe is:\n",df)
max_of_min = df.apply(lambda x: np.max(x)/np.min(x), axis=1)
print("maximum by minimum of each row:\n",max_of_min)

輸出

Dataframe is:
   0  1  2  3  4
0  2 13  4 15 86
1 60 53 86 75 45
2 37 85 40 89 88
3 67 33 80  4 74
4 85 71 11 67 81
5 56 85 95 15 94
maximum by minimum of each row:
0    43.000000
1    1.911111
2    2.405405
3    20.000000
4    7.727273
5    6.333333
dtype: float64

更新於:2021年2月25日

86 次瀏覽

啟動你的職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.