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

เขียนโปรแกรม Python แสดงสมาชิกใน Series ที่อยู่ในช่วงที่กำหนด


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

0    12 1    13 2    15 3    20 4    19 5    18 6    11

เอาต์พุต - ผลลัพธ์สมาชิกระหว่าง 10 ถึง 15

0    12 1    13 2    15 6    11

วิธีที่ 1

  • สร้าง Series

  • ใช้ between(10,15) โดยตรง

ตัวอย่าง

import pandas as pd
l = [12,13,15,20,19,18,11]
data = pd.Series(l)
print(data[data.between(10,15)])

ผลลัพธ์

0 12 1 13 2 15 6 11

วิธีที่ 2

  • สร้าง Series

  • วนลูปตรวจสอบเงื่อนไข >=10 และ <=15 เก็บในลิสต์

  • ใช้ isin() กรอง

ตัวอย่าง

import pandas as pd
l = [12,13,15,20,19,18,11]
data = pd.Series(l)
ls = []
for i in range(len(data)):
    if(data[i]>=10 and data[i]<=15):
        ls.append(data[i])
print(data[data.isin(ls)])

ผลลัพธ์

0 12 1 13 2 15 6 11