Python에서 rbind를 사용하는 방법(r과 동일)
row-bind 의 약자인 R의 rbind 함수는 데이터 프레임을 행별로 결합하는 데 사용할 수 있습니다.
pandas concat() 함수를 사용하여 Python에서 동일한 기능을 수행할 수 있습니다.
df3 = pd. concat ([df1, df2])
다음 예에서는 이 기능을 실제로 사용하는 방법을 보여줍니다.
예제 1: 동일한 열이 있는 Python에서 rbind 사용
다음 두 개의 팬더 DataFrame이 있다고 가정해 보겠습니다.
import pandas as pd #define DataFrames df1 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E'], ' points ': [99, 91, 104, 88, 108]}) print (df1) team points 0 to 99 1 B 91 2 C 104 3 D 88 4 E 108 df2 = pd. DataFrame ({' assists ': ['F', 'G', 'H', 'I', 'J'], ' rebounds ': [91, 88, 85, 87, 95]}) print (df2) team points 0 F 91 1 G 88 2:85 3 I 87 4 days 95
concat() 함수를 사용하여 이 두 DataFrame을 줄로 빠르게 연결할 수 있습니다.
#row-bind two DataFrames
df3 = pd. concat ([df1, df2])
#view resulting DataFrame
df3
team points
0 to 99
1 B 91
2 C 104
3 D 88
4 E 108
0 F 91
1 G 88
2:85
3 I 87
4 days 95
Reset_index()를 사용하여 새 DataFrame의 인덱스 값을 재설정할 수도 있습니다.
#row-bind two DataFrames and reset index values
df3 = pd. concat ([df1, df2]). reset_index (drop= True )
#view resulting DataFrame
df3
team points
0 to 99
1 B 91
2 C 104
3 D 88
4 E 108
5 F 91
6 G 88
7:85 a.m.
8 I 87
9 D 95
예제 2: 열이 같지 않은 Python에서 rbind 사용
또한 concat() 함수를 사용하여 열 수가 다른 두 DataFrame을 연결할 수 있으며 누락된 값은 단순히 NaN으로 채워집니다.
import pandas as pd #define DataFrames df1 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E'], ' points ': [99, 91, 104, 88, 108]}) df2 = pd. DataFrame ({' team ': ['F', 'G', 'H', 'I', 'J'], ' points ': [91, 88, 85, 87, 95], ' rebounds ': [24, 27, 27, 30, 35]}) #row-bind two DataFrames df3 = pd. concat ([df1, df2]). reset_index (drop= True ) #view resulting DataFrame df3 team points rebounds 0 to 99 NaN 1 B 91 NaN 2 C 104 NaN 3 D 88 NaN 4 E 108 NaN 5 F 91 24.0 6G 88 27.0 7:85 AM 27.0 8 I 87 30.0 9 D 95 35.0
추가 리소스
다음 튜토리얼에서는 Python에서 다른 일반적인 기능을 수행하는 방법을 설명합니다.
Python에서 cbind를 사용하는 방법(R과 동일)
Pandas에서 VLOOKUP을 수행하는 방법
Pandas에서 특정 값이 포함된 행을 삭제하는 방법