Pandas: 같은 이름을 공유하는 열을 병합하는 방법
다음 기본 구문을 사용하여 동일한 열 이름을 공유하는 Pandas DataFrame의 열을 병합할 수 있습니다.
#define function to merge columns with same names together def same_merge (x): return ' , '. join (x[ x.notnull ()]. astype (str)) #define new DataFrame that merges columns with same names together df_new = df. groupby (level= 0 , axis= 1 ). apply ( lambda x: x.apply (same_merge,axis= 1 ))
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Pandas에서 동일한 이름을 공유하는 열 병합
다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd import numpy as np #createDataFrame df = pd. DataFrame ({' A ': [5, 6, 8, np.nan, 4, np.nan, np.nan], ' A1 ': [np.nan, 12, np.nan, 10, np.nan, 6, 4], ' B ': [2, 7, np.nan, np.nan, 2, 4, np.nan], ' B1 ': [5, np.nan, 6, 15, 1, np.nan, 4]}) #rename columns so there are duplicate column names df. columns = [' A ', ' A ', ' B ', ' B '] #view DataFrame print (df) AABB 0 5.0 NaN 2.0 5.0 1 6.0 12.0 7.0 NaN 2 8.0 NaN NaN 6.0 3 NaN 10.0 NaN 15.0 4 4.0 NaN 2.0 1.0 5 NaN 6.0 4.0 NaN 6 NaN 4.0 NaN 4.0
두 열의 이름은 “A”이고 두 열의 이름은 “B”입니다.
다음 코드를 사용하여 동일한 열 이름을 가진 열을 병합하고 해당 값을 쉼표로 연결할 수 있습니다.
#define function to merge columns with same names together def same_merge (x): return ' , '. join (x[ x.notnull ()]. astype (str)) #define new DataFrame that merges columns with same names together df_new = df. groupby (level= 0 , axis= 1 ). apply ( lambda x: x.apply (same_merge,axis= 1 )) #view new DataFrame print (df_new) AB 0 5.0 2.0,5.0 1 6.0,12.0 7.0 2 8.0 6.0 3 10.0 15.0 4 4.0 2.0,1.0 5 6.0 4.0 6 4.0 4.0
새로운 DataFrame은 동일한 이름의 열을 병합하고 해당 값을 쉼표로 연결했습니다.
다른 구분 기호를 사용하려면 same_merge() 함수에서 쉼표 구분 기호를 다른 것으로 바꾸면 됩니다.
예를 들어 다음 코드에서는 세미콜론 구분 기호를 대신 사용하는 방법을 보여줍니다.
#define function to merge columns with same names together def same_merge (x): return ' ; '. join (x[ x.notnull ()]. astype (str)) #define new DataFrame that merges columns with same names together df_new = df. groupby (level= 0 , axis= 1 ). apply ( lambda x: x.apply (same_merge,axis= 1 )) #view new DataFrame print (df_new) AB 0 5.0 2.0;5.0 1 6.0;12.0 7.0 2 8.0 6.0 3 10.0 15.0 4 4.0 2.0;1.0 5 6.0 4.0 6 4.0 4.0
새로운 DataFrame은 동일한 이름의 열을 병합하고 해당 값을 세미콜론으로 연결했습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas에서 중복 열을 제거하는 방법
Pandas에서 모든 열 이름을 나열하는 방법
Pandas에서 이름별로 열을 정렬하는 방법