Pandas dataframe에 numpy 배열을 추가하는 방법
때로는 NumPy 배열을 pandas DataFrame에 새 열로 추가하고 싶을 수도 있습니다.
다행히도 다음 구문을 사용하면 쉽게 이 작업을 수행할 수 있습니다.
df[' new_column '] = array_name. tolist ()
이 튜토리얼에서는 이 구문의 실제 사용에 대한 몇 가지 예를 보여줍니다.
예시 1: NumPy 배열을 DataFrame의 새 열로 추가
다음 코드는 농구 선수 통계를 보관하기 위해 pandas DataFrame을 생성하고 “blocks”라는 레이블이 붙은 새 열로 NumPy 배열을 추가하는 방법을 보여줍니다.
import numpy as np import pandas as pd #create pandas DataFrame df = pd.DataFrame({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #create NumPy array for 'blocks' blocks = np. array ([2, 3, 1, 0, 2, 7, 8, 2]) #add 'blocks' array as new column in DataFrame df[' blocks '] = blocks. tolist () #display the DataFrame print(df) points assists rebounds blocks 0 25 5 11 2 1 12 7 8 3 2 15 7 10 1 3 14 9 6 0 4 19 12 6 2 5 23 9 5 7 6 25 9 9 8 7 29 4 12 2
이제 새 DataFrame에는 Blocks 라는 추가 열이 있습니다.
예 2: DataFrame의 새 열로 NumPy 행렬 추가
다음 코드는 농구 선수 통계를 보관하기 위해 pandas DataFrame을 생성하고 “blocks”라는 레이블이 붙은 새 열로 NumPy 배열을 추가하는 방법을 보여줍니다.
import numpy as np import pandas as pd #create pandas DataFrame df = pd.DataFrame({' points ': [25, 12, 15, 14, 19, 23 #create NumPy matrix mat = np.matrix([[2, 3], [1, 0], [2, 7], [8, 2], [3, 4], [7, 7], [7, 5], [6, 3]]) #add NumPy matrix as new columns in DataFrame df_new = pd. concat ([df, pd.DataFrame(mat)], axis= 1 ) #display new DataFrame print(df_new) points assists rebounds 0 1 0 25 5 11 2 3 1 12 7 8 1 0 2 15 7 10 2 7 3 14 9 6 8 2 4 19 12 6 3 4 5 23 9 5 7 7 6 25 9 9 7 5 7 29 4 12 6 3
DataFrame에 추가한 행렬의 열 이름에는 기본 열 이름인 0 과 1이 지정되어 있습니다.
df.columns 함수를 사용하여 이러한 열의 이름을 쉽게 바꿀 수 있습니다.
#rename columns
df_new. columns = ['pts', 'ast', 'rebs', 'new1', 'new2']
#display DataFrame
print(df_new)
pts ast rebs new1 new2
0 25 5 11 2 3
1 12 7 8 1 0
2 15 7 10 2 7
3 14 9 6 8 2
4 19 12 6 3 4
5 23 9 5 7 7
6 25 9 9 7 5
7 29 4 12 6 3
추가 리소스
여러 Pandas DataFrame을 스택하는 방법
인덱스에 두 개의 Pandas DataFrame을 병합하는 방법
Pandas DataFrame을 NumPy 배열로 변환하는 방법
Pandas에서 열 이름을 바꾸는 방법