<Python> ファイル名を取得

スクリプトscriptのファイル名fileを取得する。

__file__に格納されてるらしい。

例。
こういうファイルがあった時、

In [76]: more hage.py
print('hage')

読み込んで、

In [77]: import hage
hage

In [78]: dir(hage)
Out[78]: 
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

で、__file__

In [79]: hage.__file__
Out[79]: 'C:\\msys64\\home\\hageo\\python\\hage.py'

In [80]: hage.__name__
Out[80]: 'hage'

ふーん。

参考にさせてもらったところ。

www.lifewithpython.com

<Python, pandas> 文字列の置換

シリーズSeriesでの文字列置換str replace

df['column'].str.replace('','')を使う。

In [52]: df = pd.DataFrame({'a':['HAGE*', 'HAGE*']})

In [53]: df.a
Out[53]: 
0    HAGE*
1    HAGE*
Name: a, dtype: object

In [54]: df.a.str.replace('\*','')
Out[54]: 
0    HAGE
1    HAGE
Name: a, dtype: object

マニュアル。

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html?highlight=replace#pandas.Series.str.replace

データフレームDataFrameにも.replace()があった。
ただ、正規表現regexpを使うときには、regex=Trueのお呪いが必要とのこと。

In [16]: import pandas as pd

In [17]: dfa = pd.DataFrame({'a':['HAGE*', 'HAGE*']})

In [18]: dfb = pd.DataFrame({'b':['HAGE*', 'HAGE*']})

In [23]: df = pd.concat([dfa, dfb], axis=1)

In [24]: df
Out[24]: 
       a      b
0  HAGE*  HAGE*
1  HAGE*  HAGE*

In [25]: hasattr(df, 'replace')
Out[25]: True

In [26]: df.replace('HAGE', 'HAGEeeeee')
Out[26]: 
       a      b
0  HAGE*  HAGE*
1  HAGE*  HAGE*

In [27]: df.replace('HAGE*', 'HAGEeeeee')
Out[27]: 
           a          b
0  HAGEeeeee  HAGEeeeee
1  HAGEeeeee  HAGEeeeee

In [28]: import re

In [29]: df.replace(r'HAGE', 'HAGEeeeee')
Out[29]: 
       a      b
0  HAGE*  HAGE*
1  HAGE*  HAGE*

In [30]: df.replace(r'HAGE.', 'HAGEeeeee')
Out[30]: 
       a      b
0  HAGE*  HAGE*
1  HAGE*  HAGE*

In [31]: df.replace(r'HAGE.', 'HAGEeeeee', regex=True)
Out[31]: 
           a          b
0  HAGEeeeee  HAGEeeeee
1  HAGEeeeee  HAGEeeeee

In [32]: df.replace(r'HA', 'HE', regex=True)
Out[32]: 
       a      b
0  HEGE*  HEGE*
1  HEGE*  HEGE*

マニュアル。
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html?highlight=replace#pandas.DataFrame.replace

追加。
applymapでもできるじょ。

In [43]: df.applymap(lambda x: re.sub(r'HA', r'HEa', x))
Out[43]: 
        a       b
0  HEaGE*  HEaGE*
1  HEaGE*  HEaGE*

<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

できた。

ちょっとこちらで勉強した。

uxmilk.jp

<Python, peewee, Windows, Visual Studio> peewee を入れた。

オブジェクト リレイション マッパー ORM (Object Relation Mapper)の、
peeweeSQL Alchemyと比べて操作簡単そうなので、入れてみた。
が、いろいろメンドクサカッタので、メモ。

その1)
pipでインストールをしてみた。
が、エラー。```

 % pip install peewee
Collecting peewee
  Using cached peewee-2.8.5.tar.gz
Building wheels for collected packages: peewee
:
  error: Unable to find vcvarsall.bat
:

vcvarsall.batがないと怒られる。

その2)
いろいろグーグルした結果、pythonコンパイルしたC++のバージョンを確認する。

In [1]: from distutils.msvc9compiler import *

In [2]: get_build_version()
Out[2]: 14.0

In [3]: find_vcvarsall(14.0)

C++は、Version 14.0 だが、どうもpythonさんがvcvarsallを見つけれていないらしい。

その3)
いろいろグーグルした結果、Visual Studioをインストールする。
ダウンロード先。今は、Visual Studio Communityというのが、無料であるらしい。

www.visualstudio.com

その4)
その後、ただ、インストールしただけではだめなこと発覚。
インストール時にProgramming Languages -> Visal C++ -> Common Tools for Visual C++ 2015を選択する必要あり。
で、選ぶ+インストール。

f:id:nekoyukimmm:20161029191231p:plain

参考先。

stackoverflow.com

その5)
で、チェック。

In [12]: find_vcvarsall(14.0)
Out[12]: 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\vcvarsall.bat'

おおー。出たー。
ちなみに、下記探したら確かにvcvarsall.batがあった。
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC

その6)
はれてpeeweeをインストール。

 % pip install peewee
Collecting peewee
  Using cached peewee-2.8.5.tar.gz
Building wheels for collected packages: peewee
  Running setup.py bdist_wheel for peewee: started
  Running setup.py bdist_wheel for peewee: finished with status 'done'
  Stored in directory: C:\Users\Nekoyuki\AppData\Local\pip\Cache\wheels\01\37\92\e58e351fd9934c1167e2b47229ffe6f2dac238a3c3e76aa198
Successfully built peewee
Installing collected packages: peewee
Successfully installed peewee-2.8.5

成功。よかったー。

参考にさせてもらったところ。

Unreal Engine : C++ プロジェクトの作成でエラー - i++

Chainer1.5.0をWindowsにインストールする - Qiita