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

เขียนฟังก์ชัน Python ที่รับคอลัมน์ Age และ Salary ของแถวที่ 2-4 ใน DataFrame และหาค่าเฉลี่ย ผลคูณ


อินพุต -

สมมติ DataFrame ตัวอย่างดังนี้

 Id Age  salary 0 1 27   40000 1 2 22   25000 2 3 25   40000 3 4 23   35000 4 5 24   30000 5 6 32   30000 6 7 30   50000 7 8 28   20000 8 9 29   32000 9 10 27  23000

เอาต์พุต -

ผลลัพธ์ค่าเฉลี่ยและผลคูณของแถวที่เลือก

mean is Age          23.333333 salary    33333.333333 product is Age                12650 salary    35000000000000

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

เราจะทำตามขั้นตอนด้านล่าง

  • สร้าง DataFrame

  • สร้างฟังก์ชัน ตัดแถวที่ 2, 3, 4 ของคอลัมน์ age และ salary โดยใช้ iloc แล้วเก็บใน DataFrame ใหม่

df.iloc[1:4,1:]
  • คำนวณค่าเฉลี่ยและผลคูณจาก DataFrame ที่ได้

ตัวอย่าง

ดูโค้ดด้านล่างเพื่อความเข้าใจที่ดีขึ้น

import pandas as pd
def find_mean_prod():
    data = [[1,27,40000],[2,22,25000],[3,25,40000],[4,23,35000],[5,24,30000], [6,32,30000],[7,30,50000],[8,28,20000],[9,29,32000],[10,27,23000]]
    df = pd.DataFrame(data,columns=('Id','Age','salary'))
    print(df)
    print("slicing second,third and fourth rows of age and salary columns\n")
    result = df.iloc[1:4,1:]
    print("mean is\n", result.mean())
    print("product is\n", result.prod())
find_mean_prod()

ผลลัพธ์

 Id Age  salary 0 1 27   40000 1 2 22   25000 2 3 25   40000 3 4 23   35000 4 5 24   30000 5 6 32   30000 6 7 30   50000 7 8 28   20000 8 9 29   32000 9 10 27  23000 slicing second,third and fourth rows of age and salary columns mean is Age          23.333333 salary    33333.333333 product is Age                12650 salary    35000000000000