如果想保存numpy中的数组元素到一个文件中,在这方面,pandas工具的使用就会让工作方便很多。下面通过一个简单的小例子来演示一下。
首先,创建numpy中的数组:
import numpy as np
import pandas as pd
arr1 = np.arange(81).reshape(9, 9)
print("arr1的type: {}".format(type(arr1)))
print("arr1的shape: {}".format(arr1.shape))
print(arr1)
print(print('-'*100))
输出:
arr1的type:arr1的shape: (9, 9) [[ 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]]
接着,为了能够使这组数据成为可以让pandas处理的数据,需要通过这个数组创建Dataframe。
data1 = pd.Dataframe(arr1)
print("data1的type: {}".format(type(data1)))
print("data1的shape: {}".format(data1.shape))
print(data1)
print(print('-'*100))
输出:
data1的type:data1的shape: (9, 9) 0 1 2 3 4 5 6 7 8 0 0 1 2 3 4 5 6 7 8 1 9 10 11 12 13 14 15 16 17 2 18 19 20 21 22 23 24 25 26 3 27 28 29 30 31 32 33 34 35 4 36 37 38 39 40 41 42 43 44 5 45 46 47 48 49 50 51 52 53 6 54 55 56 57 58 59 60 61 62 7 63 64 65 66 67 68 69 70 71 8 72 73 74 75 76 77 78 79 80 ----------------------------------------------------------------------------------------------------
这样,就可以通过pandas中Dataframe的to_csv方法实现数据文件的存储了。具体如下:
# data1.to_csv('路径/文件名.csv')
data1.to_csv('路径/data1.csv', index=False)
# 注意要把index=False加上,否者index也会被存为一列,再读取时shape会发生变化,多了一列,shape变为(9,10)
读取文件:
data = pd.read_csv('路径/data1.csv')
完整代码:
import numpy as np
import pandas as pd
arr1 = np.arange(81).reshape(9, 9)
print("arr1的type: {}".format(type(arr1)))
print("arr1的shape: {}".format(arr1.shape))
print(arr1)
print(print('-'*100))
data1 = pd.Dataframe(arr1)
print("data1的type: {}".format(type(data1)))
print("data1的shape: {}".format(data1.shape))
print(data1)
print(print('-'*100))
# data1.to_csv('路径/文件名.csv')
data1.to_csv('路径/data1.csv', index=False)
# 注意要把index=False加上,否者index也会被存为一列,再读取时shape会发生变化,多了一列,shape变为(9,10)
data = pd.read_csv('路径/data1.csv')



