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

เขียนโปรแกรม Python สร้าง Panel จาก Dictionary ของ DataFrame และหาค่าสูงสุดของคอลัมน์แรก

หมายเหตุ: Pandas Panel ถูก deprecated แล้ว ใช้ MultiIndex DataFrame แทนในเวอร์ชันใหม่

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

  1. สร้าง dictionary key 'Column1' มีค่าเป็น DataFrame 5x3 จากข้อมูลสุ่ม
  2. สร้าง Panel จาก dictionary
  3. ใช้ p.minor_xs(0) ดึงข้อมูล minor axis index 0 (คอลัมน์แรก)
  4. หาค่าสูงสุดด้วย .max()

ตัวอย่างโค้ด

import pandas as pd
import numpy as np

data = {'Column1': pd.DataFrame(np.random.randn(5, 3))}
p = pd.Panel(data)

print("ค่าใน Panel:")
print(p['Column1'])

print("\nค่าสูงสุดของคอลัมน์แรก (minor_xs(0)):")
print(p.minor_xs(0).max())

ผลลัพธ์ตัวอย่าง

ค่าใน Panel:
          0         1         2
0  0.914209 -0.665899 -0.703097
1 -1.375634 -0.164529 -0.673326
2  1.377292  0.692793  0.390777
3 -0.899618 -1.163681  0.954463
4  0.025898  0.832265  0.173535

ค่าสูงสุดของคอลัมน์แรก (minor_xs(0)):
Column1    1.377292
dtype: float64

คำอธิบาย:

  • minor_xs(0) ดึงข้อมูลคอลัมน์ที่ 0 (minor axis) ทุก items และ major axis
  • คืนค่า Series ที่ index คือ items (Column1) และค่าคือค่าสูงสุดของคอลัมน์นั้น
  • ใน pandas ใหม่ ใช้ df.xs(0, level=1, axis=1) หรือ MultiIndex slicing แทน