วิธีส่งออก pandas dataframe ไปยังไฟล์ข้อความ


คุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อส่งออก DataFrame ของ pandas ไปยังไฟล์ข้อความ:

 #specify path for export
path = r' c:\data_folder\my_data.txt '

#export DataFrame to text file
with open (path, ' a ') as f:
    df_string = df. to_string (header= False , index= False )
    f. write (df_string)

อาร์กิวเมนต์ header=False บอกให้ pandas ไม่รวมแถวส่วนหัวในไฟล์ข้อความ และ index=False บอกให้ pandas ไม่รวมคอลัมน์ดัชนีในไฟล์ข้อความ

คุณสามารถละเว้นข้อโต้แย้งเหล่านี้ได้ หากคุณต้องการรวมแถวส่วนหัวหรือคอลัมน์ดัชนีในไฟล์ข้อความ

ตัวอย่างต่อไปนี้แสดงวิธีการใช้ไวยากรณ์นี้เพื่อส่งออก DataFrame ของ pandas ไปยังไฟล์ข้อความในทางปฏิบัติ

ตัวอย่าง: ส่งออก Pandas DataFrame ไปยังไฟล์ข้อความ

สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับผู้เล่นบาสเกตบอลต่างๆ:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   ' points ': [18, 22, 19, 14, 14, 11, 20, 28],
                   ' assists ': [5, 7, 7, 9, 12, 9, 9, 4],
                   ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
print (df)

  team points assists rebounds
0 A 18 5 11
1 B 22 7 8
2 C 19 7 10
3 D 14 9 6
4 E 14 12 6
5 F 11 9 5
6 G 20 9 9
7:28 4 12

เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อส่งออก DataFrame นี้ไปยังไฟล์ข้อความชื่อ Basketball_data.txt :

 #specify path for export
path = r' c:\data_folder\basketball_data.txt '

#export DataFrame to text file
with open (path, ' a ') as f:
    df_string = df. to_string (header= False , index= False )
    f. write (df_string)

หากฉันนำทางไปยังโฟลเดอร์ที่ฉันส่งออกไฟล์นี้ ฉันจะสามารถดูไฟล์ข้อความได้:

ค่าในไฟล์ข้อความสอดคล้องกับค่าใน DataFrame ของแพนด้า

โปรดทราบว่าแถวส่วนหัวและคอลัมน์ดัชนีได้ถูกลบออกจาก DataFrame ตามที่เราระบุไว้

หากคุณต้องการเก็บแถวส่วนหัวและคอลัมน์ดัชนีไว้ในไฟล์ข้อความ คุณสามารถใช้ไวยากรณ์ต่อไปนี้:

 #specify path for export
path = r' c:\data_folder\basketball_data.txt '

#export DataFrame to text file (keep header row and index column)
with open (path, ' a ') as f:
    df_string = df. to_string ()
    f. write (df_string)

หากฉันนำทางไปยังโฟลเดอร์ที่ฉันส่งออกไฟล์นี้ ฉันจะสามารถดูไฟล์ข้อความได้:

โปรดทราบว่าทั้งแถวส่วนหัวและคอลัมน์ดัชนีจะรวมอยู่ในไฟล์ข้อความ

ที่เกี่ยวข้อง: วิธีใช้ “with open” ใน Python

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:

วิธีส่งออก Pandas DataFrame เป็น CSV
วิธีส่งออก Pandas DataFrame ไปยัง Excel
วิธีส่งออก Pandas DataFrame ไปยัง JSON

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *