根據列值從 Pandas DataFrame 中選擇行


以下步驟可以根據列值從 DataFrame 中選擇行 -

  • 建立一個二維、大小可變、可能為異構表格資料,df

  • 列印輸入 DataFrame。

  • x==2 時,使用 df.loc[df["x"]==2] 列印 DataFrame。

  • 類似地,當 (x >= 2) (x < 2) 時,列印 DataFrame。

示例

 動態演示

import pandas as pd

df = pd.DataFrame(
   {
      "x": [5, 2, 1, 9],
      "y": [4, 1, 5, 10],
      "z": [4, 1, 5, 0]
   }
)

print "Given DataFrame is:
", df print "When column x value == 2:
", df.loc[df["x"] == 2] print "When column x value >= 2:
", df.loc[df["x"] >= 2] print "When column x value < 2:
", df.loc[df["x"] < 2]

輸出

Given DataFrame is:
   x  y  z
0  5  4  4
1  2  1  1
2  1  5  5
3  9 10  0

When column x value == 2:
  x  y  z
1 2  1  1

When column x value >= 2:
   x  y  z
0  5  4  4
1  2  1  1
3  9 10  0

When column x value < 2:
  x  y  z
2 1  5  5

更新於: 2021 年 8 月 30 日

814 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始使用
廣告
© . All rights reserved.