Home  >  Article  >  Backend Development  >  How to save an array in Python

How to save an array in Python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-25 11:42:376605browse

If you want to save the array elements in numpy to a file, it is certainly possible to write it through pure Python file writing, but it always feels a little less convenient. In this regard, the use of pandas tools will make the work much easier. Let's demonstrate it through a simple example.

How to save an array in Python

First, create the array in numpy.

In [18]: arr1 = np.arange(100).reshape(10,10)
In [19]: arr1
Out[19]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
  [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
  [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
  [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
  [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
  [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
  [70, 71, 72, 73, 74, 75, 76, 77, 78, 79],
  [80, 81, 82, 83, 84, 85, 86, 87, 88, 89],
  [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]])

Next, in order to make this set of data into data that can be processed by pandas, a DataFrame needs to be created from this array.

Related recommendations: "Python Video Tutorial"

In [20]: data1 = DataFrame(arr1)

In this way, the data file can be stored through the to_csv method of DataFrame in pandas. The details are as follows:

In [21]: data1.to_csv('data1.csv')
In [22]: cat data1.csv
,0,1,2,3,4,5,6,7,8,9
0,0,1,2,3,4,5,6,7,8,9
1,10,11,12,13,14,15,16,17,18,19
2,20,21,22,23,24,25,26,27,28,29
3,30,31,32,33,34,35,36,37,38,39
4,40,41,42,43,44,45,46,47,48,49
5,50,51,52,53,54,55,56,57,58,59
6,60,61,62,63,64,65,66,67,68,69
7,70,71,72,73,74,75,76,77,78,79
8,80,81,82,83,84,85,86,87,88,89
9,90,91,92,93,94,95,96,97,98,99

Look back at the stored data format:

In [23]: data1
Out[23]:
 0 1 2 3 4 5 6 7 8 9
0 0 1 2 3 4 5 6 7 8 9
1 10 11 12 13 14 15 16 17 18 19
2 20 21 22 23 24 25 26 27 28 29
3 30 31 32 33 34 35 36 37 38 39
4 40 41 42 43 44 45 46 47 48 49
5 50 51 52 53 54 55 56 57 58 59
6 60 61 62 63 64 65 66 67 68 69
7 70 71 72 73 74 75 76 77 78 79
8 80 81 82 83 84 85 86 87 88 89
9 90 91 92 93 94 95 96 97 98 99
In [24]: type(data1)
Out[24]: pandas.core.frame.DataFrame

From the above results, we can see that when converted into DataFrame, the data information adds row and column header information.

The effect of opening a csv file through spreadsheet software is as follows:

How to save an array in Python

The above is the detailed content of How to save an array in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn