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

เขียนโปรแกรมใน Python เพื่อส่งออก dataframe ที่กำหนดเป็นรูปแบบไฟล์ Pickle และอ่านเนื้อหาจากไฟล์ Pickle


สมมติว่าคุณมี dataframe และผลลัพธ์สำหรับการส่งออกไปยังไฟล์ pickle และอ่านเนื้อหาจากไฟล์เป็น,

Export to pickle file:
Read contents from pickle file:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington

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

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนด้านล่าง -

  • กำหนดดาต้าเฟรม

  • ส่งออก dataframe เป็นรูปแบบ pickle และตั้งชื่อเป็น 'pandas.pickle'

df.to_pickle('pandas.pickle')
  • อ่านเนื้อหาจากไฟล์ 'pandas.pickle' แล้วเก็บเป็นผลลัพธ์

result = pd.read_pickle('pandas.pickle')

ตัวอย่าง

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

import pandas as pd
df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"],
                     'City' : ["Shimla","Sydney","Lucknow","Wellington"]
                  })
print("Export to pickle file:")
df.to_pickle('pandas.pickle')
print("Read contents from pickle file:")
result = pd.read_pickle('pandas.pickle')
print(result)

ผลลัพธ์

Export to pickle file:
Read contents from pickle file:
  Fruits    City
0 Apple    Shimla
1 Orange   Sydney
2 Mango    Lucknow
3 Kiwi    Wellington