<Python, pandas, Beautiful Soup> Excel から DataFrame への変換
PythonでエクセルExcel
のデータを読み込んで、データフレームDataFrame
にしたい。
最近のExcelさんは中身がバイナリでなくて、XML
ってことは知っていたので、Beautiful Soup
と組み合わせてみた。
と、いうことで、ファイル読み込み。
普通にリードしてみる。
In [14]: f = open('Hagehage.xls', mode='r') In [15]: s = f.read() --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-15-8c49373f2620> in <module>() ----> 1 s = f.read() UnicodeDecodeError: 'cp932' codec can't decode byte 0x9d in position 15322332: illegal multibyte sequence
エラー。
なんかファイルのできが悪くて、最後の方で読み込めない。
しばし考えて、1行ごとに読み込めば! との考えに至る。
やってみる。
In [16]: f = open('Hagehage.xls', mode='r') In [17]: s = '' In [18]: for line in f: ...: s = s + line ...: --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-18-c7a5d6f43181> in <module>() ----> 1 for line in f: 2 s = s + line 3 UnicodeDecodeError: 'cp932' codec can't decode byte 0x9d in position 3292: illegal multibyte sequence In [19]: len(s) Out[19]: 15033496
オッケー!
変数s
に取り込めた。
じゃー変換。
In [20]: from bs4 import BeautifulSoup In [21]: import pandas as pd In [22]: df = pd.DataFrame() In [23]: soup = BeautifulSoup(s, 'xml') In [24]: Row = soup.findAll('Row') In [25]: for r, row in enumerate(Row): ...: Cell = row.findAll('Cell') ...: for c, col in enumerate(Cell): ...: df.loc[r, c] = col.Data.string ...: In [26]: len(df) Out[26]: 4393
できた。
ちょっとこちらで勉強した。