본문 바로가기

파이썬

excel에서 드래그로 인덱스 증가(숫자 늘리기)[기초]

반응형

엑셀에서 간혹 인덱스를 늘려서

동등하게 비교를 해야할 때가 있다.

손수 J1 셀의 오른쪽 하단 꼭지점을 눌러

오른쪽으로 드래그 하면

오른쪽으로 인덱스가 늘어났다.


이런 기능을 가진 파이썬 스크립트를

만들어보자! 작년에 한 3일 고민해서 만들었던 로직인데

하나의 파일에 해당해서 늘리는 방법만 우선

소개해보고자 한다.

 

import pandas as pd

sample = pd.read_excel("holo_single_dcc.xlsx")

colab을 활용해서 간단하게

파일을 담아둔다.

 

(colab에 파일 loading하는 방법 소개:

google drive 구글드라이브를 코랩에 로딩(colab load)하기 (tistory.com))

 

sample 데이터를 출력해보면

위의 엑셀 파일의 데이터프레임과 동일함을 알 수 있다.

def add_index(wanted_index, sample_file):
    fpocket_original_index = len(sample_file.columns)
    for i in range(0, (wanted_index - fpocket_original_index + 1)):
        num = fpocket_original_index + i
        sample_file = sample_file.reindex(columns=sample_file.columns.tolist() + [f"pocket{'%03d'%(num)}"])
    sample_file.to_excel("holo_single_dcc_r.xlsx", index=False, header=True)  

그런 다음,

wanted_index(늘리기로 희망하는 인덱스 값)을 입력해

해당 함수를 활용해서 돌리고

sample_file의 output을 export하는 과정을 거친다.

위와 동일하게 16까지 늘린다고 가정하고

add_index(16, sample)

input을 16, sample데이터로 입력하면?

다음과 같이 인덱스가 늘어난

엑셀파일을 get할 수 있다.

반응형