我将一个csv文件加载到'dataset'中并尝试执行dataset.head(),但报错了。如何在不指定具体行数的情况下检查numpy数组的头或尾?
如果你需要使用头部函数,只需使用dataset[:10]
对数组进行切片。
如果你需要使用尾部函数,只需使用dataset[-10:]
对数组进行切片。
*
符号来表示可迭代对象中的“剩余”部分。>>> import numpy as np
>>> np.array((1,2,3))
array([1, 2, 3])
>>> head, *tail = np.array((1,2,3))
>>> head
1
>>> tail
[2, 3]
这个运作良好:
def nparray_tail(x: np.array, n:int):
"""
Returns tail N elements of array.
:param x: Numpy array.
:param n: N elements to return on end.
:return: Last N elements of array.
"""
if n == 0:
return x[0:0] # Corner case: x[-0:] will return the entire array but tail(0) should return an empty array.
else:
return x[-n:] # Normal case: last N elements of array.
作为额外的好处,这个修复了 @feedMe 答案中一个不直观的边界情况: dataset[-0:]
返回整个数组,而不是当请求最后 0 个元素时应该得到的空数组。这与 Pandas 中的 .tail()
函数是一致的。
array[:head]
和array[tail:]
来检查它。您需要指定头部(head)和尾部(tail),因为NumPy没有默认值(不像Pandas,您可以指定行数)。 - a_guest