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

เขียนโปรแกรม Python นับจำนวนข้อมูลประเภท integer, float, string ใน Series


อินพุต - สมมติคุณมี series

0    1 1    2 2    python 3    3 4    4 5    5 6    6.5

เอาต์พุต -

Total number of integer, float and string elements are, integer count: 5 float count: 1 string count: 1

วิธีแก้ปัญหา

ทำตามขั้นตอนด้านล่าง

  • สร้าง Series

  • ใช้ filter กับ lambda ตรวจสอบ type เป็น int, float, str แล้วนับจำนวน

len(pd.Series(filter(lambda x:type(x)==int,data))
len(pd.Series(filter(lambda x:type(x)==float,data))
len(pd.Series(filter(lambda x:type(x)==str,data))

ตัวอย่าง

import pandas as pd
ls = [1,2,"python",3,4,5,6.5]
data = pd.Series(ls)
print("integer count:",len(pd.Series(filter(lambda x:type(x)==int,data))))
print("float count:",len(pd.Series(filter(lambda x:type(x)==float,data))))
print("string count:",len(pd.Series(filter(lambda x:type(x)==str,data))))

ผลลัพธ์

integer count: 5 float count: 1 string count: 1