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

แสดง Pandas DataFrame โดยไม่มี Index ด้วย to_string(index=False)

ใช้เมธอด to_string() พร้อมพารามิเตอร์ index=False เพื่อแปลง DataFrame เป็นสตริงแสดงผลโดยไม่แสดงคอลัมน์ Index

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

import pandas as pd

# สร้าง DataFrame มี custom index
df = pd.DataFrame(
    [[10, 15], [20, 25], [30, 35]],
    index=['x', 'y', 'z'],
    columns=['a', 'b']
)

print("DataFrame พร้อม Index:\n", df)

# เลือกแถวด้วย loc
print("\nแถว index 'x':\n", df.loc['x'])

# แสดง DataFrame โดยไม่มี Index
print("\nDataFrame ไม่มี Index:\n", df.to_string(index=False))

ผลลัพธ์

DataFrame พร้อม Index:
    a   b
x  10  15
y  20  25
z  30  35

แถว index 'x':
a    10
b    15
Name: x, dtype: int64

DataFrame ไม่มี Index:
   a   b
  10  15
  20  25
  30  35

วิธีนี้เหมาะสำหรับการแสดงผลหรือ Export ไฟล์ที่ไม่ต้องการ Index