
本文详细讲解了在使用 NumPy 的 insert 函数时,如何避免意外替换现有行,并正确地将新行插入到 NumPy 数组中。文章通过示例代码和问题分析,阐述了 np.insert 的正确用法,以及需要注意的关键点,帮助读者掌握 NumPy 数组操作的技巧。
NumPy 的 insert 函数是一个强大的工具,用于在数组的指定位置插入值。然而,如果不正确地使用它,可能会导致数据被替换而不是插入,这通常不是我们期望的结果。本文将深入探讨 np.insert 的使用方法,并提供一个实际示例,说明如何避免常见的错误。
np.insert 函数的基本语法如下:
numpy.insert(arr, obj, values, axis)
其中:
关键点:np.insert 不会修改原始数组,而是返回一个新的数组。 这是一个非常重要的特性,也是导致很多问题的根源。
在实际应用中,一个常见的错误是直接在循环中使用 np.insert,期望它能修改原始数组。例如:
import numpy as np
file = np.loadtxt("name.csv", skiprows=1, dtype='<U70', delimiter =',')
fileShape = file.shape
rows = fileShape[0]
cols = fileShape[1]
for row in range(rows):
for col in range(cols):
if (col == 4 and row + 1 < rows):
if (file[row][col] != file[row+1][col]):
temp = file[row+1]
temp[5] = ""
np.insert(file, row+1, [temp], axis=0) # 错误:没有将返回值赋给 file这段代码的意图是在满足特定条件时,在 file 数组的指定行插入新行。然而,由于 np.insert 返回的是一个新的数组,而原始的 file 数组并没有被修改,所以最终的结果可能不是我们想要的。
正确的做法是将 np.insert 的返回值赋给 file:
import numpy as np
import pandas as pd
file = np.loadtxt("name.csv", skiprows=1, dtype='<U70', delimiter =',')
fileShape = file.shape
rows = fileShape[0]
cols = fileShape[1]
for row in range(rows):
for col in range(cols):
if (col == 4 and row + 1 < rows):
if (file[row][col] != file[row+1][col]):
temp = file[row+1].copy() # use copy to avoid modifying the original array
temp[5] = ""
file = np.insert(file, row+1, [temp], axis=0) # insert the new row into the array
outfile = pd.DataFrame(file)
outfile.to_csv("OutFile.csv")此外,为了避免修改原始数组中的数据,建议使用 .copy() 方法创建 temp 变量,确保对 temp 的修改不会影响到 file 数组。
代码解释:
假设我们有一个名为 name.csv 的 CSV 文件,内容如下:
ccType,number,date,payee,total,indAmt,memo,category mastercard,30,11/21/2022,Bluejam,287.24,44.33,,Sports mastercard,30,11/23/2022,Fanoodle,287.24,95.95,,Health mastercard,30,11/25/2022,Eazzy,287.24,1.2,,Automotive mastercard,30,11/26/2022,Dabfeed,287.24,68.97,,Games mastercard,30,11/30/2022,Jaloo,287.24,76.79,,Games mastercard,50,7/4/2023,Shufflebeat,317.13,91.91,,Sports mastercard,50,7/4/2023,Meembee,317.13,94.69,,Toys mastercard,50,7/5/2023,Jabberbean,317.13,67.01,,Computers mastercard,50,7/28/2023,Wikibox,317.13,33.18,,Movies mastercard,50,7/29/2023,Shufflebeat,317.13,30.34,,Automotive
运行上述修正后的代码后,生成的 OutFile.csv 文件内容如下:
,0,1,2,3,4,5,6,7 0,mastercard,30,11/21/2022,Bluejam,287.24,44.33,,Sports 1,mastercard,30,11/23/2022,Fanoodle,287.24,95.95,,Health 2,mastercard,30,11/25/2022,Eazzy,287.24,1.2,,Automotive 3,mastercard,30,11/26/2022,Dabfeed,287.24,68.97,,Games 4,mastercard,30,11/30/2022,Jaloo,287.24,76.79,,Games 5,mastercard,50,7/4/2023,Shufflebeat,317.13,,,Sports 6,mastercard,50,7/4/2023,Shufflebeat,317.13,91.91,,Sports 7,mastercard,50,7/4/2023,Meembee,317.13,94.69,,Toys 8,mastercard,50,7/5/2023,Jabberbean,317.13,67.01,,Computers 9,mastercard,50,7/28/2023,Wikibox,317.13,33.18,,Movies 10,mastercard,50,7/29/2023,Shufflebeat,317.13,30.34,,Automotive
可以看到,在 "mastercard,30" 和 "mastercard,50" 之间,成功插入了一行,并且第 6 列的值被设置为空字符串。
使用 NumPy 的 insert 函数时,务必记住以下几点:
掌握这些要点,可以避免在使用 np.insert 时出现意外的替换行为,并正确地插入数据。
以上就是NumPy insert 函数:避免替换并正确插入行的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号