我正在学习python,在处理对象时遇到了一些麻烦。我试图寻找一个解决方案,但它无处可去,所以我问你们。
我想获得一个对象的前X列,但我不能在每一行中都有相同的大小。
我有这个对象:
array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
[45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
[50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)
我想得到这样的东西:
array([[45, 45, 45, 50],
[45, 45, 45, 50],
[45, 45, 45, 50],
[50, 51, 52, 55]])
我该怎么做才能解决这个问题? 谢谢你的帮助
阿尔瓦罗
答案 0 :(得分:3)
怎么样?
import numpy as np
data = np.array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
[45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
[50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)
newData = np.array([d[:4] for d in data])
答案 1 :(得分:0)
您可能需要一个更通用的解决方案,您还可以按如下方式指定行数:
import numpy as np
arr = np.array([[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 52],
[45, 45, 45, 50, 51, 50, 50, 50, 51, 50, 51, 52, 55],
[45, 45, 45, 50, 51, 50, 52, 50, 50, 50, 51],
[50, 51, 52, 55, 50, 52, 50, 50, 50, 51, 50, 51]], dtype=object)
def slice_array(arr, num_cols, num_rows=None):
if num_rows:
return np.array([row[:num_cols] for row in arr[:num_rows]])
return np.array([row[:num_cols] for row in arr])
res1 = slice_array(arr, 4, 2)
res2 = slice_array(arr, 4) # Like in your case
<强>结果:强>
>>> res1
array([[45, 45, 45, 50],
[45, 45, 45, 50]])
>>> res2
array([[45, 45, 45, 50],
[45, 45, 45, 50],
[45, 45, 45, 50],
[50, 51, 52, 55]])