[엑셀과 함께 춤을] 그렇지만 가끔 이렇게 삐긋합니다

새로운 세션으로 질문을 계속 해보면 이런 식으로 삐긋하는 경우가 있습니다.

분명 방금 전까지도 시트의 목록도 잘 보여주었는데 말이죠.

image


코드를 보여달라고 해봅시다. 뭔가 느낌이 쎄합니다.

시트 목록을 보여달라고 했는데, 그냥 통째로 엑셀 파일을 읽었습니다.

이건 그냥 엑셀의 모든 텍스트를 읽고 답변하는 것일 뿐입니다.

image


강제로 코드 인터프리터를 수행하게 해보겠습니다.

말로 그냥 시키면 됩니다. “코드 인터프리터를 쓰세요.”

그러면 또 잘 동작합니다.

image

import pandas as pd

# Load the Excel file
excel_file = pd.ExcelFile('뭔가통합 3.xlsx')

# Get the sheet names
sheet_names = excel_file.sheet_names

# Print the sheet names
print("Sheet names in the Excel file are:", sheet_names)

엑셀 파일이 가지고 있는 시트를 인식하니 각 시트마다 흩어져 있는 정보를 모아서 보여달라고 해봅시다.

그런데 결과가 안좋습니다. 한글 프롬프트 열을 못찾는다고 합니다.

image


코드를 살펴보면 ‘한글 프롬프트’라는 컬럼을 찾으려고 합니다. 사실 나는 열이라고 한적이 없거든요.

컬럼이라면 엑셀에서는 세로축인데, 한글 프롬프트는 세로 축이라기 보다는 가로 축인 행으로 되어 있습니다.

import pandas as pd

# Load the Excel file
file_path = '뭔가통합 3.xlsx'
xls = pd.ExcelFile(file_path)

# Initialize a list to store the prompts
prompts = []

# Iterate through each sheet in the Excel file
for sheet_name in xls.sheet_names:
    # Load the sheet into a DataFrame
    df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl')
    
    # Check if '한글 프롬프트' column exists in the sheet
    if '한글 프롬프트' in df.columns:
        # Extract the '한글 프롬프트' values and add them to the list
        for prompt in df['한글 프롬프트']:
            prompts.append({'Sheet Name': sheet_name, '한글 프롬프트': prompt})

# Convert the list to a DataFrame
prompts_df = pd.DataFrame(prompts)

# Display the DataFrame
print(prompts_df)

이녀석이 열, 컬럼을 찾으니 두번째 시트의 열이 무엇이 있는지 물어봅시다.

못찾습니다. 뭐지 세개의 언네임드 컬럼이라….

image

import pandas as pd

# Load the Excel file
file_path = '뭔가통합 3.xlsx'

# Load the second sheet
sheet_name = '2025-05-30-최정우'
df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl')

# Get the column names
column_names = df.columns.tolist()

print(f"The columns in the sheet '{sheet_name}' are: {column_names}")

혹시나 해서 행으로 물어봅시다. ‘한글 프롬프트’ 라는 행이 있는지 물어봅시다.

어!! 나옵니다. 찾아요.

image


그런데 코드를 보면 ‘한글 프롬프트’ 라는 값이 있는 셀(이 포함된 행)을 그냥 찾는 거네요.

동작 하기는 하겠지만 쪼금 마음이 그렇습니다.

import pandas as pd

# Load the Excel file
file_path = '뭔가통합 3.xlsx'
xls = pd.ExcelFile(file_path)

# Load the second sheet
sheet_name = xls.sheet_names[1]
df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl')

# Find the row where '한글 프롬프트' is present and get the adjacent cell value
prompt_row = df[df.apply(lambda row: row.astype(str).str.contains('한글 프롬프트').any(), axis=1)]

# Display the row containing '한글 프롬프트'
prompt_row

조금 더 명확하게 해봅시다. ‘한글 프롬프트’ 라는 셀은 두번째 열에 있습니다.

그러니까 그 옆에 있는 열3 의 값이 사실 내가 필요한 거죠. 그냥 그렇게 말해 봅시다.

가져옵니다. 각 시트의 값들을 찾아서 표로 잘 정리해 줍니다.

image


코드를 보니. ㅎㅎㅎ

‘한글 프롬프트가’ 값으로 있는 행을 찾아 그 행의 열3 을 찾는 로직으로 되어 있습니다.

되긴 되는데, 썩 좋은 로직은 아닌 것 같습니다.

import pandas as pd

# Load the Excel file
file_path = '뭔가통합 3.xlsx'
xls = pd.ExcelFile(file_path)

# Initialize a list to store the results
results = []

# Iterate through each sheet
for sheet_name in xls.sheet_names:
    # Load the sheet into a DataFrame
    df = pd.read_excel(file_path, sheet_name=sheet_name, engine='openpyxl')
    
    # Search for '한글 프롬프트' in all cells
    for idx, row in df.iterrows():
        if '한글 프롬프트' in row.values:
            # Extract the value from the third column (index 2) if it exists
            if len(row) > 2:
                prompt_value = row.iloc[2]
                results.append({'Sheet Name': sheet_name, '한글 프롬프트': prompt_value})

# Convert the results to a DataFrame
results_df = pd.DataFrame(results)

# Display the results
results_df