使用 Python 編寫程式,從 DataFrame 中列印“A”等級學生的姓名。


輸入 -

Assume, you have DataFrame,
 Id  Name Grade
0 1 stud1   A
1 2 stud2   B
2 3 stud3   C
3 4 stud4   A
4 5 stud5   A

輸出 -

以及“A”等級學生的姓名結果,

0    stud1
3    stud4
4    stud5

解決方案

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

  • 定義 DataFrame

  • 將值與 DataFrame 進行比較

df[df['Grade']=='A']
  • 將結果儲存在另一個 DataFrame 中並獲取姓名。

示例

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

import pandas as pd
data =
[[1,'stud1','A'],[2,'stud2','B'],[3,'stud3','C'],[4,'stud4','A'],[5,'stud5','A']]
df = pd.DataFrame(data,columns=('Id','Name','Grade'))
print("DataFrame is\n",df)
print("find the A grade students name\n")
result = df[df['Grade']=='A']
print(result['Name'])

輸出

DataFrame is
 Id Name Grade
0 1 stud1  A
1 2 stud2  B
2 3 stud3  C
3 4 stud4  A
4 5 stud5  A
find the A grade students name
0    stud1
3    stud4
4    stud5
Name: Name, dtype: object

更新於: 2021年2月24日

566 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告