아래 코드는 Pandas 라이브러리의 to_excel
함수를 이용해 DataFrame을 Excel 파일로 저장하는 방법입니다:
import os
import pandas as pd
df = pd.DataFrame(data)
filename = 'output.xlsx'
# If file does not exist, write with header
# If file exists, append without writing header
if not os.path.isfile(filename):
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
df.to_excel(writer, index=False)
else: # else it exists so append without writing the header
with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer:
df.to_excel(writer, header=False, index=False)
그러나 불행히도 openpyxl
엔진은 기존 Excel 파일에 새로운 데이터를 추가하는 기능을 지원하지 않습니다. 따라서 위 코드는 기존의 Excel 파일에 새로운 데이터를 추가하는 대신, 새로운 시트를 추가합니다.
기존의 Excel 파일에 새로운 데이터를 추가하려면 먼저 Excel 파일을 읽어 들여 모든 데이터를 DataFrame으로 변환한 후, 새로운 데이터를 이 DataFrame에 추가하고 이를 다시 Excel 파일로 저장해야 합니다.
import pandas as pd
filename = 'output.xlsx'
if os.path.isfile(filename):
df_old = pd.read_excel(filename)
df_new = pd.concat([df_old, df])
else:
df_new = df
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
df_new.to_excel(writer, index=False)
이 코드는 기존의 Excel 파일과 새로운 DataFrame의 열 이름이 같고 순서도 동일하다고 가정합니다. 만약 이 가정이 맞지 않다면 추가적인 데이터 처리가 필요합니다.
`np.sqrt()` 함수와 제곱 연산자 `**` 비교 (0) | 2023.06.16 |
---|---|
numpy에서 squared norm 계산하는 방법 (0) | 2023.06.15 |
두 NumPy 배열을 비교하는 방법 (0) | 2023.04.06 |
np.linalg.solve, sp.sparse.linalg.spsolve, gmres 장단점 비교 (0) | 2023.04.05 |
댓글 영역