To save a DataFrame (df) to a file using the pandas package in Python, you can use various methods depending on the desired file format. The most common formats are CSV, Excel, and Pickle. Once saved, you can restore it in another Python script by reading from the saved file.
Here's how you can do both operations:
Saving a DataFrame to a file:
To CSV:
python
import pandas as pd
# Assuming df is your DataFrame
df.to_csv('filename.csv', index=False)
To Excel:
python
# Requires openpyxl or xlwt to be installed if you are using newer or older versions of Excel, respectively.
df.to_excel('filename.xlsx', index=False)
To Pickle:
python
df.to_pickle('filename.pkl')
Restoring a DataFrame from a file:
From CSV:
python
import pandas as pd
df = pd.read_csv('filename.csv')
From Excel:
python
df = pd.read_excel('filename.xlsx')
From Pickle:
python
df = pd.read_pickle('filename.pkl')
Example usage across two scripts:
Script 1: Saving the DataFrame
python
# save_df.py
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
# Save the DataFrame to a CSV file
df.to_csv('my_dataframe.csv', index=False)
Script 2: Restoring the DataFrame
python
# load_df.py
import pandas as pd
# Load the DataFrame from the CSV file
df = pd.read_csv('my_dataframe.csv')
# Now df is restored and can be used
print(df)
When you run save_df.py, it will save the DataFrame to a CSV file named my_dataframe.csv. Then, when you run load_df.py, it will read the CSV file and restore the DataFrame.
Remember to ensure that the file you are saving to and reading from is accessible from both scripts, which might involve setting the correct file paths if the scripts are running in different directories.