Write a NumPy array to an Excel file and read it back
NumPy: I/O Operations Exercise-12 with Solution
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:
import numpy as np
import pandas as pd
# Create a NumPy array
data_array = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Define the path to the Excel file
excel_file_path = 'data.xlsx'
# Convert the NumPy array to a Pandas DataFrame
df = pd.DataFrame(data_array, columns=['Column1', 'Column2', 'Column3'])
# Write the DataFrame to an Excel file
df.to_excel(excel_file_path, index=False)
# Read the Excel file back into a Pandas DataFrame
df_loaded = pd.read_excel(excel_file_path)
# Convert the DataFrame back to a NumPy array
loaded_array = df_loaded.to_numpy()
# Print the original and loaded NumPy arrays
print("Original NumPy Array:")
print(data_array)
print("\nLoaded NumPy Array from Excel File:")
print(loaded_array)
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.
Python-Numpy Code Editor:
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