NumPy 将数组转换为CSV文件

NumPy 将数组转换为CSV文件

Numpy是Python编程语言中的一个库, 其全称为Numerical Python. 它用于在更短的时间内进行数学、科学和统计计算. 使用numpy函数的输出将是一个数组. 通过一个名为savetxt()的函数,可以将numpy函数创建的数组存储在CSV文件中。

Numpy数组转换为.csv文件

CSV的全称为Comma Separated Values,即逗号分隔的值。这是数据科学中使用最广泛的文件格式。它以表格的形式存储数据,其中列持有数据字段,行持有数据。

.csv文件中的每一行都以逗号或由用户自定义的分隔符字符分隔。在数据科学中,我们必须使用pandas库来处理csv文件。

使用numpy库的loadtxt()函数,也可以以numpy数组格式读取csv文件中的数据。

语法

以下是使用savetxt()函数将numpy数组转换为CSV文件的语法。

numpy.savetxt(file_name,array,delimiter = ‘,’)

其中,

  • numpy 是库的名称。

  • savetxt 是将数组转换为.csv文件的函数。

  • file_name 是csv文件的名称。

  • array 是需要转换为.csv文件的输入数组。

示例

为了将数组元素转换为csv文件,我们需要将文件名和输入数组作为输入参数传递给 savetxt() 函数,同时设置分隔符=’,’,然后数组将被转换为csv文件。以下是示例。

import numpy as np
a = np.array([23,34,65,78,45,90])
print("The created array:",a)
csv_data = np.savetxt("array.csv",a,delimiter = ",")
print("array converted into csv file")
data_csv = np.loadtxt("array.csv",delimiter = ",")
print("The data from the csv file:",data_csv)

输出

The created array: [23 34 65 78 45 90]
array converted into csv file
The data from the csv file: [23. 34. 65. 78. 45. 90.]

示例

让我们看一个另外的例子,在这个例子中我们使用numpy库的savetxt()函数将2D数组数据转换为CSV文件。

import numpy as np
a = np.array([[23,34,65],[78,45,90]])
print("The created array:",a)
csv_data = np.savetxt("2d_array.csv",a,delimiter = ",")
print("array converted into csv file")
data_csv = np.loadtxt("array.csv",delimiter = ",")
print("The data from the csv file:",data_csv)

输出

The created array: [[23 34 65]
[78 45 90]]
array converted into csv file
The data from the csv file: [[23. 34. 65.]
[78. 45. 90.]]

示例

在以下示例中,我们将“_”作为CSV文件的分隔符,而不是“,”。

import numpy as np
a = np.array([[23,34,65,87,3,4],[78,45,90,53,5,3]],int)
print("The created array:",a)
csv_data = np.savetxt("2d_array.csv",a,delimiter = "_")
print("array converted into csv file")
data_csv = np.loadtxt("2d_array.csv",delimiter = "_")
print("The data from the csv file:",data_csv)

输出

以下是将数组转化为csv文件的输出结果。

The created array: [[23 34 65 87 3 4]
[78 45 90 53 5 3]]
array converted into csv file
The data from the csv file: [[23. 34. 65.]
[78. 45. 90.]]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程