Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - เลือก Subset ของ Pandas DataFrame

บทนำ

ใช้วงเล็บเหลี่ยมเลือกคอลัมน์เดี่ยวหรือหลายคอลัมน์จาก DataFrame

ตัวอย่าง

  1. เลือกคอลัมน์เดี่ยว Car:
    dataFrame['Car']
  2. เลือก 2 คอลัมน์ Car และ Units:
    dataFrame[['Car', 'Units']]

โค้ดเต็ม

import pandas as pd

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
print("\nReading the CSV file...\n", dataFrame)

res1 = dataFrame['Car']
print("\nDisplaying only one column Car : \n", res1)

res2 = dataFrame[['Car', 'Units']]
print("\nDisplaying two columns : \n", res2)

ผลลัพธ์

คอลัมน์ Car: Series ของชื่อรถ
คอลัมน์ Car และ Units: DataFrame 2 คอลัมน์