2023. 8. 29. 21:04ㆍHackerRank-Python
Concatenate | HackerRank
Use the concatenate function on 2 arrays.
www.hackerrank.com
문제
Task
You are given two integer arrays of size N X P and M X P (N & M are rows, and P is the column). Your task is to concatenate the arrays along axis 0.
Input Format
The first line contains space separated integers N,M and P.
The next N lines contains the space separated elements of the P columns.
After that, the next M lines contains the space separated elements of the P columns.
Output Format
Print the concatenated array of size (N + M) X P.
=> N행 P열, M행 P행 의 array를 (N+M)행 P열 의 array로 합쳐라. axis=0(행 방향, 세로)
코드
import numpy as np
N, M, P = map(int, input().split())
a = []
for i in range(N):
a.append(
list(map(int, input().split()))
)
b = []
for _ in range(M):
b.append(
list(map(int, input().split()))
)
a_arr = np.array(a)
b_arr = np.array(b)
print(np.concatenate((a_arr,b_arr), axis=0))
# print(np.concatenate((a,b), axis=0)) 놀랍게도 됨
노트
concatenate()
np.concatenate((a,b), [axis= ])
concatenate: 사슬 같이 잇다
배열을 결합시킬 때 사용
- 첫번째 파라미터: 합칠 array들
- 두 번째 파라미터: 연결할 축을 지정. 0이면 행 방향(세로로), 1이면 열 방향(가로로), 1차원 array에서는 사용 불가
import numpy
array_1 = numpy.array([1,2,3])
array_2 = numpy.array([4,5,6])
array_3 = numpy.array([7,8,9])
print(numpy.concatenate((array_1, array_2, array_3)))
#Output
[1 2 3 4 5 6 7 8 9]
import numpy
array_1 = numpy.array([[1,2,3],[0,0,0]])
array_2 = numpy.array([[0,0,0],[7,8,9]])
print(numpy.concatenate((array_1, array_2), axis = 1))
#Output
[[1 2 3 0 0 0]
[0 0 0 7 8 9]]
print(numpy.concatenate((array_1, array_2), axis = 0))
#Output
[[1 2 3]
[0 0 0]
[0 0 0]
[7 8 9]]
numpy.arrary()
arr = np.array(data, dtype=np.float64)
- np.array()함수의 두번째 인자로 data의 자료형을 지정할 수 있음
# 정답 코드에 활용
import numpy as np
N, M, P = map(int, input().split())
a_arr = np.array([input().split() for _ in range(N)], int)
b_arr = np.array([input().split() for _ in range(M)], int)
print(np.concatenate((a_arr,b_arr), axis=0))
두 번째 시도
import numpy
N, M, P = map(int, input().split())
arr_1 = numpy.array(
[list(map(int, input().split())) for _ in range(N)]
)
arr_2 = numpy.array(
[list(map(int, input().split())) for _ in range(M)]
)
print(numpy.concatenate((arr_1, arr_2), axis = 0))
- 두 array를 리스트 comprehesion구문으로 만들기
참조
[파이썬 numpy] 배열 합치기 (concatenate 메소드) + axis 개념
[파이썬 numpy] 배열 합치기 (concatenate 메소드) + axis 개념 concatenate 메소드는 선택한 축(axis)의 방향으로 배열을 연결해주는 메소드입니다. concatenate 는 '사슬 같이 연결하다'는 의미입니다. 1,2,3차원
pybasall.tistory.com
5-3. numpy · 왕초보를 위한 파이썬 활용하기
cycorld.gitbooks.io
https://bard.google.com/share/cf6bf0b9f404
bard.google.com
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Numpy > Eye and Identity (0) | 2023.08.31 |
---|---|
Prepare > Python > Numpy > Zeros and Ones (0) | 2023.08.30 |
Prepare > Python > Numpy > Transpose and Flatten (0) | 2023.08.28 |
Prepare > Python > Numpy > Shape and Reshape (0) | 2023.08.27 |
Prepare > Python > Numpy > Arrays (0) | 2023.08.26 |