編寫一個 Python 函式,接受 DataFrame 的 Age 和 Salary 列的第二、三、四行作為輸入,並找到這些值的平均值和乘積。


輸入

假設,示例 DataFrame 為:

 Id Age  salary
0 1 27   40000
1 2 22   25000
2 3 25   40000
3 4 23   35000
4 5 24   30000
5 6 32   30000
6 7 30   50000
7 8 28   20000
8 9 29   32000
9 10 27  23000

輸出

給定切片行的平均值和乘積的結果為:

mean is
Age          23.333333
salary    33333.333333
product is
Age                12650
salary    35000000000000

解決方案

為了解決這個問題,我們將遵循以下方法。

  • 定義一個 DataFrame

  • 建立一個函式,使用 iloc 函式切片 Age 和 Salary 列的第二、三、四行,並將結果儲存在 result DataFrame 中。

df.iloc[1:4,1:]
  • 從 result DataFrame 中計算平均值和乘積。

示例

讓我們看看以下實現,以便更好地理解。

import pandas as pd
def find_mean_prod():
   data = [[1,27,40000],[2,22,25000],[3,25,40000],[4,23,35000],[5,24,30000], [6,32,30000],[7,30,50000],[8,28,20000],[9,29,32000],[10,27,23000]]
   df = pd.DataFrame(data,columns=('Id','Age','salary'))
   print(df)
   print("slicing second,third and fourth rows of age and salary columns\n")
   result = df.iloc[1:4,1:]
   print("mean is\n", result.mean())
   print("product is\n", result.prod())
find_mean_prod()

輸出

 Id Age  salary
0 1 27   40000
1 2 22   25000
2 3 25   40000
3 4 23   35000
4 5 24   30000
5 6 32   30000
6 7 30   50000
7 8 28   20000
8 9 29   32000
9 10 27  23000
slicing second,third and fourth rows of age and salary columns
mean is
Age          23.333333
salary    33333.333333
product is
Age                12650
salary    35000000000000

更新於: 2021年2月24日

501 次檢視

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告