使用 Python 編寫程式,在一個給定的 DataFrame 中查詢員工 ID 和薪資對應的最小年齡。


輸入 -

假設,您有一個 DataFrame

DataFrame is
 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

輸出 -

並且,員工 ID 和薪資對應的最小年齡的結果為:

 Id Salary
1 2 25000

解決方案

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

  • 定義一個 DataFrame

  • 設定條件,檢查 DataFrame 的 Age 列是否等於最小年齡。將其儲存在 result DataFrame 中。

result = df[df['Age']==df['Age'].min()]
  • 從 result DataFrame 中篩選 Id 和 Salary。定義如下:

result[['Id','Salary']]

示例

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

import pandas as pd
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("DataFrame is\n",df)
print("find the minimum age of an employee id and salary\n")
result = df[df['Age']==df['Age'].min()]
print(result[['Id','Salary']])

輸出

DataFrame is
 Id    Age   Salary0 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
find the minimum age of an employee id and salary
 Id Salary
1 2 25000

更新時間: 2021-02-24

846 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.