Write a NumPy array to an Excel file and read it back
12. Excel File Read/Write via Pandas
Write a NumPy array to an Excel file using a library like pandas and then read it back into a NumPy array.
Sample Solution:
Python Code:
Output:
Original NumPy Array: [[10 20 30] [40 50 60] [70 80 90]] Loaded NumPy Array from Excel File: [[10 20 30] [40 50 60] [70 80 90]]
Explanation:
- Import NumPy and Pandas Libraries: Import the NumPy and Pandas libraries to handle arrays and data frames.
- Create NumPy Array: Define a NumPy array with some example data.
- Define Excel File Path: Specify the path where the Excel file will be saved.
- Convert Array to DataFrame: Convert the NumPy array to a Pandas DataFrame, providing column names for better readability.
- Write DataFrame to Excel: Use to_excel() to write the DataFrame to an Excel file, setting index=False to omit row indices.
- Read Excel File to DataFrame: Use read_excel() to read the contents of the Excel file back into a Pandas DataFrame.
- Convert DataFrame to Array: Convert the loaded DataFrame back to a NumPy array using to_numpy().
- Finally print the original NumPy array and the loaded array to verify that the data was saved and read correctly.
For more Practice: Solve these Related Problems:
- Write a Numpy program to convert an array to a DataFrame and then export it to an Excel file with multiple sheets.
- Write a Numpy program to read data from an Excel file into a DataFrame and then convert it to a NumPy array with preserved data types.
- Write a Numpy program to export a numeric array to an Excel file using Pandas and then read back specific columns for analysis.
- Write a Numpy program to convert a multi-sheet Excel file into separate NumPy arrays and then perform cross-array computations.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: How to save and load a large NumPy array to and from a compressed .npz file?
Next: How to read numeric data from a JSON file into a NumPy array?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics