Pandas: 두 개의 dataframe을 빼는 방법


다음 구문을 사용하여 한 팬더 DataFrame을 다른 팬더 DataFrame에서 뺄 수 있습니다.

 df1. subtract (df2)

각 DataFrame에 문자 열이 있는 경우 먼저 이를 각 DataFrame의 인덱스 열로 이동해야 할 수 있습니다.

 df1. set_index (' char_column '). subtract ( df2.set_index (' char_column '))

다음 예에서는 실제로 각 구문을 사용하는 방법을 보여줍니다.

예 1: 두 개의 Pandas DataFrame 빼기(숫자 열만 해당)

숫자 열만 있는 다음 두 개의 팬더 DataFrame이 있다고 가정해 보겠습니다.

 import pandas as pd

#create first DataFrame
df1 = pd. DataFrame ({' points ': [5, 17, 7, 19, 12, 13, 9, 24],
                    ' assists ': [4, 7, 7, 6, 8, 7, 10, 11]})

print (df1)

   assist points
0 5 4
1 17 7
2 7 7
3 19 6
4 12 8
5 13 7
6 9 10
7 24 11

#create second DataFrame
df2 = pd. DataFrame ({' points ': [4, 22, 10, 3, 7, 8, 12, 10],
                    ' assists ': [3, 5, 5, 4, 7, 14, 9, 5]})

print (df2)

   assist points
0 4 3
1 22 5
2 10 5
3 3 4
4 7 7
5 8 14
6 12 9
7 10 5

다음 코드는 두 DataFrame 사이에서 해당 값을 빼는 방법을 보여줍니다.

 #subtract corresponding values between the two DataFrames
df1. subtract (df2)

	assist points
0 1 1
1 -5 2
2 -3 2
3 16 2
4 5 1
5 5 -7
6 -3 1
7 14 6

예 2: 두 개의 Pandas DataFrame 빼기(문자 열과 숫자 열의 혼합)

각각 team 이라는 문자 열이 있는 다음 두 개의 팬더 DataFrame이 있다고 가정해 보겠습니다.

 import pandas as pd

#create first DataFrame
df1 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                    ' points ': [5, 17, 7, 19, 12, 13, 9, 24],
                    ' assists ': [4, 7, 7, 6, 8, 7, 10, 11]})

print (df1)

  team points assists
0 to 5 4
1 B 17 7
2 C 7 7
3 D 19 6
4 E 12 8
5 F 13 7
6 G 9 10
7:24 a.m. 11

#create second DataFrame
df2 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                    ' points ': [4, 22, 10, 3, 7, 8, 12, 10],
                    ' assists ': [3, 5, 5, 4, 7, 14, 9, 3]})

print (df2)

  team points assists
0 to 4 3
1 B 22 5
2 C 10 5
3 D 3 4
4 E 7 7
5 F 8 14
6 G 12 9
7:10 a.m. 3

다음 코드는 열을 각 DataFrame의 인덱스 열로 이동한 후 두 DataFrame 사이에서 해당 값을 빼는 방법을 보여줍니다.

 #move 'team' column to index of each DataFrame and subtract corresponding values
df1. set_index (' team '). subtract ( df2.set_index (' team '))

	assist points
team		
At 1 1
B-52
C -3 2
D 16 2
E 5 1
F 5 -7
G -3 1
H 14 8

추가 리소스

다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

Pandas: 두 열의 차이점을 찾는 방법
Pandas: 두 줄의 차이점을 찾는 방법
팬더:두 열을 빼는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다