xlwings tutorial - 데이터 계산하여 붙여 넣기

xlwings

XLWings 사용하기

xlwings로 Excel 데이터 열어서 계산하기
In [ ]:
#Pokemon.xlsx
#xlwings를 열겠습니다.
import xlwings as xw
#pandas를 가져옵니다.
import pandas as pd
#numpy를 가져옵니다.
import numpy as np
In [ ]:
#active sheet를 가져옵니다.
sht=xw.sheets.active
![image.png](attachment:image.png)
In [ ]:
#active sheet의 전체 데이터를 가져옵니다.
#header가 있고 index가 없는 데이터이기 때문에 index=False로 설정합니다.
#만약 header도 없으면 header=False로 합니다.
df=sht[0,0].options(pd.DataFrame,expand='table',index=False).value
In [25]:
#컬럼 이름을 확인해보겠습니다.
df.columns
Out[25]:
Index(['#', 'Name', 'Type', 'Total', 'HP', 'Attack', 'Defense',
       'Special Attack', 'Special Defense', 'Speed', 'AD_ratio', 'AD_type'],
      dtype='object')
In [26]:
#첫 번째 레코드를 살펴봅니다.
df.iloc[0,:]
Out[26]:
#                        001
Name               Bulbasaur
Type                   GRASS
Total                    318
HP                        45
Attack                    49
Defense                   49
Special Attack            65
Special Defense           65
Speed                     45
AD_ratio                   1
AD_type             Defender
Name: 0, dtype: object
In [ ]:
#방어당 공격 비율을 계산해봅니다.
df['AD_ratio']=df['Attack']/df['Defense']
In [ ]:
#성격을 판단합니다.
df['AD_type']=np.where(df['AD_ratio']>1,'Attacker','Defender')
In [27]:
df.iloc[0,:]
Out[27]:
#                        001
Name               Bulbasaur
Type                   GRASS
Total                    318
HP                        45
Attack                    49
Defense                   49
Special Attack            65
Special Defense           65
Speed                     45
AD_ratio                   1
AD_type             Defender
Name: 0, dtype: object
In [ ]:
#새로 작성된 데이터를 K1 열에 삽입합니다.
sht.range("k1").options(pd.Series,index=False).value=df['AD_ratio']
In [24]:
#새로 작성된 데이터를 L1 열에 삽입합니다.
sht.range("L1").options(pd.Series,index=False).value=df['AD_type']
![image.png](attachment:image.png)
In [18]:
#데이터를 새로운 워크시트로 붙여 넣어봅시다.
book=xw.books.active

![image.png](attachment:image.png)
In [22]:
book.sheets['pandas'][0,0].options(index=False).value=df

댓글

이 블로그의 인기 게시물

R에서 csv 파일 읽는 법