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

จะแยกชื่อค่าและนับจาก value_counts () ใน Pandas ได้อย่างไร


หากต้องการแยกชื่อค่าและจำนวน ให้เราสร้าง DataFrame ที่มี 4 คอลัมน์ก่อน -

dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})

ดึงชื่อค่าและนับสำหรับคอลัมน์เฉพาะรถ -

res = dataFrame['Car'].value_counts()

ดึงชื่อค่าและนับสำหรับคอลัมน์เฉพาะ หน่วยที่ขาย -

res = dataFrame['Units Sold'].value_counts()

ตัวอย่าง

ต่อไปนี้เป็นรหัสที่สมบูรณ์ -

import pandas as pd

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})

print("DataFrame ...\n",dataFrame)

res = dataFrame['Car'].value_counts()
print("\nDisplaying value name and counts from the column Car:\n",res)

res = dataFrame['Units Sold'].value_counts()
print("\nDisplaying value name and counts from the column Units Sold:\n",res)

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

DataFrame ...
        Car   Cubic Capacity   Reg Price   Units Sold
0       BMW            2000         7000          200
1   Mustang            1800         1500          120
2     Tesla            1500         5000          150
3   Mustang            2500         8000          120
4  Mercedes            2200         9000          210
5     Tesla            3000         6000          250
6      Audi            2000         1500          220

Displaying value name and counts from the column Car:
Mustang    2
Tesla      2
Audi       1
BMW        1
Mercedes   1
Name: Car, dtype: int64

Displaying value name and counts from the column Units Sold:
120   2
150   1
220   1
210   1
250   1
200   1
Name: Units Sold, dtype: int64