I'm trying to save two arrays (arr1, arr2) to a file horizontally. The problem is the two arrays have different lengths. So I can't use np.v_stack() to concatenate them. The two arrays I want to save: arr1 (5, 3):
array([[-15.220009 , 10.6649946, -0.8999929],
[-15.000009 , 11.3639946, -1.5949929],
[-14.036009 , 9.9939946, -0.3249929],
[-12.958009 , 10.9589946, 0.2050071],
[-12.179009 , 10.3039946, 0.5970071]])
arr2 (4, 3):
array([[-15.809009 , 10.0499946, -1.4429929],
[-15.804009 , 10.9649946, -0.1329929],
[-13.677009 , 9.3459946, -1.1249929],
[-13.420009 , 11.4869946, 1.0390071]])
The output I'm expecting:
-15.220009, 10.6649946, -0.8999929, -15.809009, 10.0499946, -1.4429929
-15.000009, 11.3639946, -1.5949929, -15.804009, 10.9649946, -0.1329929
-14.036009, 9.9939946, -0.3249929, -13.677009, 9.3459946, -1.1249929
-12.958009, 10.9589946, 0.2050071, -13.420009, 11.4869946, 1.0390071
-12.179009, 10.3039946, 0.5970071
I have searched on google but can't find a useful solution.
arr = [[-15.220009, 10.6649946, -0.8999929],
[-15.000009, 11.3639946, -1.5949929],
[-14.036009, 9.9939946, -0.3249929],
[-12.958009, 10.9589946, 0.2050071],
[-12.179009, 10.3039946, 0.5970071]]
arr2 = [[-15.809009, 10.0499946, -1.4429929],
[-15.804009, 10.9649946, -0.1329929],
[-13.677009, 9.3459946, -1.1249929],
[-13.420009, 11.4869946, 1.0390071]]
for i in range(max(len(arr), len(arr2))):
str1 = (", ".join(map(str, arr[i]))) if i < len(arr) else ""
str2 = (", ".join(map(str, arr2[i]))) if i < len(arr2) else ""
print str1 + ', ' + str2
This doesn't save it to a file, but you could replace the print with saving to a file. Note that if the first array is shorter than the second, the second one's extra rows will appear below the first array.
Edit
One Line solution
print "\n".join([", ".join(map(str, (arr[i] if i < len(arr) else []) + (arr2[i] if i < len(arr2) else []))) for i in range(max(len(arr), len(arr2)))])
I have got the expected output with several steps. First, I use np.hstack() to concatenate the slice of the larger with the smaller. Then open a file and write the arr3 and arr1[-1:] (the leftover portion of the larger) to a file in order using np.savetxt(). For example:
arr3=np.hstack((arr1[:-1], arr2))
with open('out.dat', 'w') as output:
np.savetxt(output, arr3, fmt=','.join(['% 12.7f']*6))
np.savetxt(output, arr1[-1:], fmt=','.join(['% 12.7f']*3))
x = np.concatenate((arr,arr2))
np.save('fileName', x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.