杰瑞科技汇

Python如何保存数组数据?

Here are the most common ways to save a NumPy array to a file, depending on what you plan to do with the data later.

Python如何保存数组数据?-图1
(图片来源网络,侵删)

Save as a .npy file (Best for Python/NumPy)

This is the standard way to save a single NumPy array. It preserves the data type and shape perfectly.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Save the array
np.save('my_array.npy', arr)
# Load the array back
loaded_arr = np.load('my_array.npy')
print(loaded_arr)

Save as a .npz file (Best for multiple arrays)

If you have more than one array, you can compress them into a single .npz file.

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Save multiple arrays
np.savez('multiple_arrays.npz', array1=arr1, array2=arr2)
# Load them back
data = np.load('multiple_arrays.npz')
print(data['array1'])
print(data['array2'])

Save as a .csv or .txt file (Best for Excel or other languages)

If you need to open the array in Excel, MATLAB, or read it with a language other than Python, save it as a text file.

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Save as a CSV file
np.savetxt('my_array.csv', arr, delimiter=',')
# Load it back
loaded_arr = np.loadtxt('my_array.csv', delimiter=',')
print(loaded_arr)

Save as a .csv using Pandas (Best for data with headers)

If your array represents tabular data and you need column or row headers, use the Pandas library.

Python如何保存数组数据?-图2
(图片来源网络,侵删)
import pandas as pd
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Save with column names
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])
df.to_csv('my_data.csv', index=False)
# Load it back
loaded_df = pd.read_csv('my_data.csv')
print(loaded_df.values) # .values converts it back to a NumPy array

Save as a .json file (Best for web APIs and JavaScript)

If you need to pass the array to a web frontend or a NoSQL database, JSON is the best format.

import json
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Save as JSON
with open('my_array.json', 'w') as f:
    json.dump(arr.tolist(), f) # .tolist() converts the NumPy array to a standard Python list
# Load it back
with open('my_array.json', 'r') as f:
    loaded_list = json.load(f)
    loaded_arr = np.array(loaded_list)
print(loaded_arr)

Summary: Which should you use?

  • Loading back into Python? Use .npy (Fastest and smallest file size).
  • Multiple arrays? Use .npz.
  • Opening in Excel? Use .csv (np.savetxt or pandas).
  • Sending to a web browser? Use .json.
分享:
扫描分享到社交APP
上一篇
下一篇