pandas 등 자주 쓰는데 헷갈리는 기능 정리

svenskpotatis·2023년 9월 16일
0

헷갈리는 것, 자주 쓰는 것 정리

📌

  • .find() 은 정규 표현식을 지원하지 않는다. 즉,
'a\rAa'.find(r'[a-z]\r[A-Z]') 

에서 -1을 return함.

  • re 모듈을 사용하자.
import re

text = 'a\rAa'
pattern = r'[a-z]\r[A-Z]'

match = re.search(pattern, text)

if match:
    print(f"Match found at index {match.start()}")
else:
    print("No match found.")

📌 dropna()

  • df.dropna(axis=0, how'any, thresh=None, subset=None, inplace=True)
  • df['columnName'].dropna()
  • 결측값 제거

📌 특정 내용이 column 안에 있는지 확인

target_value = 'desired_value'
result = df['column_name'] == target_value
desired_rows = df[result]

📌 column 순서 바꾸기

import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Define the new order of columns
new_order = ['B', 'A', 'C']

# Reorder the columns
df = df[new_order]

print(df)

📌 column 보기

column_A_df = df[['A']]

📌 column 길이 조정

pd.set_option('max_colwidth', 1000)  # 크게
pd.set_option('max_colwidth', 30)   # 작게

📌 df[df['B'] == 'x']['A']

📌 list -> dict의 key나 value

my_list = ['apple', 'banana', 'cherry']
my_dict = {key: None for key in my_list}

print(my_dict)

>>>
{'apple': None, 'banana': None, 'cherry': None}

📌 ex

  • chat gpt 에게 예쁘게 바꿔달라고 한 코드 (중복확인)

전:

for key, value in codeDict.items():
    for codes in codelist3:
        for code in codes:
            if code == key:
                codeDict[key] += 1

print(codeDict)

후:

codeDict = {key: value + sum(code == key for codes in codelist3 for code in codes) for key, value in codeDict.items()}

column 이름 있는 빈 dataframe 만들기

columns=['col1', 'col2', 'col3', 'col4', 'col5']
df = pd.DataFrame(columns=columns)

concat

  • ignore_index
# 기존 index 유지
df = pd.concat([df1, df2]) 

# 기존 index 무시
df = pd.concat([df1, df2], ignore_index=True) 

0개의 댓글