
本文详细讲解了在使用 NumPy 的 insert 函数时,如何避免意外替换现有行,并正确地将新行插入到 NumPy 数组中。文章通过示例代码和问题分析,阐述了 np.insert 的正确用法,以及需要注意的关键点,帮助读者掌握 NumPy 数组操作的技巧。
NumPy 的 insert 函数是一个强大的工具,用于在数组的指定位置插入值。然而,如果不正确地使用它,可能会导致数据被替换而不是插入,这通常不是我们期望的结果。本文将深入探讨 np.insert 的使用方法,并提供一个实际示例,说明如何避免常见的错误。
理解 np.insert 的工作原理
np.insert 函数的基本语法如下:
numpy.insert(arr, obj, values, axis)
其中:
arr: 要进行插入操作的数组。obj: 插入的位置。可以是一个整数,表示插入到指定索引之前;也可以是一个整数数组,表示在多个位置插入。values: 要插入的值。可以是一个标量,也可以是一个数组。如果 values 是一个数组,它的形状应该与 arr 在 axis 维度上的形状相匹配。axis: 指定插入的轴。默认情况下,axis=None,这意味着 arr 会被展平(flatten),然后插入 values,最后再重塑成原来的形状。
关键点:np.insert 不会修改原始数组,而是返回一个新的数组。 这是一个非常重要的特性,也是导致很多问题的根源。
常见错误及解决方法
在实际应用中,一个常见的错误是直接在循环中使用 np.insert,期望它能修改原始数组。例如:
import numpy as npfile = np.loadtxt("name.csv", skiprows=1, dtype='<U70', delimiter =',')fileShape = file.shaperows = 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 npimport pandas as pdfile = np.loadtxt("name.csv", skiprows=1, dtype='<U70', delimiter =',')fileShape = file.shaperows = 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 arrayoutfile = pd.DataFrame(file)outfile.to_csv("OutFile.csv")
此外,为了避免修改原始数组中的数据,建议使用 .copy() 方法创建 temp 变量,确保对 temp 的修改不会影响到 file 数组。
代码解释:
temp = file[row+1].copy(): 这行代码创建了 file 数组中下一行 (row+1) 的一个副本,并将其赋值给 temp。使用 .copy() 是至关重要的,因为直接赋值(temp = file[row+1])只会创建一个指向原始数据的视图,任何对 temp 的修改都会反映到 file 数组中。temp[5] = “”: 这行代码将 temp 数组的第 6 个元素(索引为 5)设置为空字符串。file = np.insert(file, row+1, [temp], axis=0): 这行代码使用 np.insert 函数在 file 数组的 row+1 位置插入 temp 数组。axis=0 参数指定沿着行的方向插入。重要的是,np.insert 函数返回一个新的数组,因此需要将返回值赋值给 file,以更新 file 数组的内容。
完整示例
假设我们有一个名为 name.csv 的 CSV 文件,内容如下:
ccType,number,date,payee,total,indAmt,memo,categorymastercard,30,11/21/2022,Bluejam,287.24,44.33,,Sportsmastercard,30,11/23/2022,Fanoodle,287.24,95.95,,Healthmastercard,30,11/25/2022,Eazzy,287.24,1.2,,Automotivemastercard,30,11/26/2022,Dabfeed,287.24,68.97,,Gamesmastercard,30,11/30/2022,Jaloo,287.24,76.79,,Gamesmastercard,50,7/4/2023,Shufflebeat,317.13,91.91,,Sportsmastercard,50,7/4/2023,Meembee,317.13,94.69,,Toysmastercard,50,7/5/2023,Jabberbean,317.13,67.01,,Computersmastercard,50,7/28/2023,Wikibox,317.13,33.18,,Moviesmastercard,50,7/29/2023,Shufflebeat,317.13,30.34,,Automotive
运行上述修正后的代码后,生成的 OutFile.csv 文件内容如下:
,0,1,2,3,4,5,6,70,mastercard,30,11/21/2022,Bluejam,287.24,44.33,,Sports1,mastercard,30,11/23/2022,Fanoodle,287.24,95.95,,Health2,mastercard,30,11/25/2022,Eazzy,287.24,1.2,,Automotive3,mastercard,30,11/26/2022,Dabfeed,287.24,68.97,,Games4,mastercard,30,11/30/2022,Jaloo,287.24,76.79,,Games5,mastercard,50,7/4/2023,Shufflebeat,317.13,,,Sports6,mastercard,50,7/4/2023,Shufflebeat,317.13,91.91,,Sports7,mastercard,50,7/4/2023,Meembee,317.13,94.69,,Toys8,mastercard,50,7/5/2023,Jabberbean,317.13,67.01,,Computers9,mastercard,50,7/28/2023,Wikibox,317.13,33.18,,Movies10,mastercard,50,7/29/2023,Shufflebeat,317.13,30.34,,Automotive
可以看到,在 “mastercard,30” 和 “mastercard,50” 之间,成功插入了一行,并且第 6 列的值被设置为空字符串。
总结
使用 NumPy 的 insert 函数时,务必记住以下几点:
np.insert 不会修改原始数组,而是返回一个新的数组。必须将 np.insert 的返回值赋给原始数组变量,才能真正修改数组。使用 .copy() 方法创建需要修改的行的副本,避免修改原始数组中的数据。根据需要设置 axis 参数,指定插入的轴。
掌握这些要点,可以避免在使用 np.insert 时出现意外的替换行为,并正确地插入数据。
以上就是NumPy insert 函数:避免替换并正确插入行的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1375624.html
微信扫一扫
支付宝扫一扫