달력

3

« 2024/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
728x90
반응형

2개의 데이터 프레임을 한줄씩 교차로 합쳐보는 것을 한번 해보겠습니다.

구글링을 해봐도 검색 스킬이 부족해서 인지 제가 원하는 그런 예제가 없더라구요.

그리고, dataframe의 기능들을 살펴봐도 잘 모르겠구요.

그래서 임시방편으로 한줄씩 읽어서 교차적으로 concat 을 이용해서 붙여보았습니다.

두개의 데이터프레임을 합치기 붙이고자 하는 데이터프레임의 컬럼수는 맞아야 합니다.

df1과 df2과 각각의 로우에 대해서 불러와야 하므로 loc 함수를 이용해서 한줄을 불러옵니다.

불러왔지만, 데이터가 series 형식처럼 row가 아닌 column 으로 배치가 되어 T 를 사용해서 transform 해줍니다.

이렇게 변형되는 것을 확인 후에는 for 문을 사용하여 한줄씩 붙여보도록 하겠습니다.

위와 같이 한줄씩 concat으로 적용된 것을 볼 수 있습니다.

 

여담이지만, 이렇게 코랩에서 간단하게 연습을 해보고 파이참으로 이 코드를 적용해봤을때는 

왜 그런지 또~~^^;; 적용이 안되더라구요.. 에잇!

 

그래서, 파이참에서 적용할때는 각각의 데이터프레임을 걍 리스트로 만들고

그 리스트를 하나씩 순차적으로 돌아가면서 리스트를 형성 뒤 데이터프레임으로 만들었습니다. ㅠ.ㅠ

노가다....젠장.

 

혹시나 다른 좋은 방법 있으시면 좀 알려주세요~!!!!!!!!!

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

indicator를 포함하는 2개의 머지는 그냥 합치면 된다.

그런데, 3개 이상을 할려면 어떻게 해야 할까...!!!

 

이번에도 역시 chatGPT에게 물어봤다.

You can use the merge() function from the pandas library to merge three dataframes with the indicator option in Python. Here's an example code:

pandas 라이브러리의 merge() 함수를 사용하여 Python에서 표시기 옵션을 사용하여 세 개의 데이터 프레임을 병합할 수 있습니다. 다음은 예제 코드입니다:
import pandas as pd

# create three dataframes
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value1': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value2': [5, 6, 7, 8]})
df3 = pd.DataFrame({'key': ['A', 'B', 'F', 'G'], 'value3': [9, 10, 11, 12]})

# merge the dataframes using 'key' as the join key and specify the indicator option
merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator=True)

print(merged_df)
In this example, we create three dataframes df1, df2, and df3, each with a column named 'key'. We then use the merge() function to merge the dataframes, specifying 'key' as the join key and 'outer' as the merge method (which includes all keys from both dataframes). Finally, we set the indicator parameter to True to include a column indicating the source of each row in the merged dataframe. The result is stored in the merged_df variable and printed to the console.

이 예제에서는 각각 'key'라는 열이 있는 세 개의 데이터프레임 df1, df2, df3을 만듭니다. 그런 다음 merge() 함수를 사용하여 데이터 프레임을 병합하고, 조인 키로 'key'를 지정하고 병합 방법(두 데이터 프레임의 모든 키를 포함하는 병합 방법)으로 'outer'를 지정합니다. 마지막으로, 병합된 데이터 프레임에 각 행의 출처를 나타내는 열을 포함하도록 표시기 매개 변수를 True로 설정합니다. 결과는 merged_df 변수에 저장되고 콘솔에 인쇄됩니다.

위와 같이 답변을 받을 수 있었고, 이번에는 번역툴을 파파고나 아닌 딥엘이라는 번역기를 사용해서 작업을 해보았다.

(나쁘지는 않은듯~)

 

하지만!!!!

코드가 먹히지를 않는다!!!!

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-35e2c9af28c5> in <module>
      8 # merge the dataframes using 'key' as the join key and specify the indicator option
      9 merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
---> 10 merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator=True)
     11 
     12 print(merged_df)

2 frames
/usr/local/lib/python3.8/dist-packages/pandas/core/reshape/merge.py in _indicator_pre_merge(self, left, right)
    762                 )
    763         if self.indicator_name in columns:
--> 764             raise ValueError(
    765                 "Cannot use name of an existing column for indicator column"
    766             )

ValueError: Cannot use name of an existing column for indicator column

'Search Stack overflow' 를 눌러서 바로 검색을 해봤다.

https://stackoverflow.com/questions/48669316/valueerror-cannot-use-name-of-an-existing-column-for-indicator-column

 

ValueError: Cannot use name of an existing column for indicator column

I need to work on a problem where I will have a data frame,say df, with Name & age & I need to generate another dataframe with name & gender in for loop & I need to merge the data f...

stackoverflow.com

여기에서 살펴보면 indicator의 이름이 중복되어서 나온다는 것이다.

그래서 거기서에서 알려주는데로 

3번째 하는 머지는 indicator='exists' 로 이름을 명명해줬다. 그랬더니 제대로 된 출력을 할 수 있었다.

 

import pandas as pd

# create three dataframes
df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value1': [1, 2, 3, 4]})
df2 = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value2': [5, 6, 7, 8]})
df3 = pd.DataFrame({'key': ['A', 'B', 'F', 'G'], 'value3': [9, 10, 11, 12]})

# merge the dataframes using 'key' as the join key and specify the indicator option
merged_df = pd.merge(df1, df2, on='key', how='outer', indicator=True)
merged_df = pd.merge(merged_df, df3, on='key', how='outer', indicator='exists')

print(merged_df)

이를 응용해서 3개 이상을 'outer' 머지를 하고 싶은 경우에는 indicator=' ' 를 활용하면 된다.

 

indicator를 쓰게 되면 양쪽 자료에 있는 중복, 고유한 자료들을 표시할 수 있어서 추후에 연산작업이나 그래프로 나타내기가 수월하다.

 

감사합니다.

728x90
반응형
:
Posted by 패치#노트
728x90
반응형

데이터 프레임을 자주 사용하다 보면

각 셀별로 데이터의 길이를 구해서 판단을 해야 하는 경우도 발생하게 된다.

 

예를 들어 아래와 같은 전화번호 컬럼이 있다고 가정해보자.

import pandas as pd
data = [['John', 45, '010-1234-4589'],['Will', 20, '02-1234-1324'],['Ai', 13, '123']]
df = pd.DataFrame(data,columns=['Name','Age', 'Telephone'])
df

 

다양한 방법들이 존재하겠지만,

전화번호 영역에 다른 이상한 것이 끼어있다면 아래와 같이 len( ) 함수를 이용해서 간단하게 처리 할 수 있다.

 

df['Telephone'].apply(len)

len 함수를 사용하게 되면 각 row 별로 리턴해준다.

아래와 같이 조건에 맞게 설정한뒤 다시 데이터프레임으로 저장하면 쓸데없는 값을 쉽게 해결할 수 있다.

df = df[df['Telephone'].apply(len) >= 12]
df

 

간단하지만 많은 부분에서 사용할 수 있을 것라고 생각해본다.

728x90
반응형
:
Posted by 패치#노트