やりたいこと
Pythonで自作モジュールを作って、呼び出す場合について。
特に、カレントではないところにモジュールフォルダがある場合にそこからの呼び出し方。
参考文献
// HTML4.0の頃から見てるけど、とほほさんはずっとWebを更新していて偉いなあ。
ソリューション
# 以下のような階層で入っているとする
(current)
├─ test.py # 呼び出し元のコード
└─ /hapy_mod # モジュールが入っているフォルダ
└─ ham.py # モジュールそのもの
ham.py
# 必要なモジュールのインポート
import pandas as pd
#-------------------------------------------------
# Excelの指定行からデータを取り出しDataFrameにして返す
# f_name: Excelのファイル名
# s_name: Excelのシート名
# row_num: Excelの行番号(1オリジン)
#-------------------------------------------------
def get_df_from_excel(f_name, s_name, row_num=1):
print(" -> get_df_from_excel: " + f_name + ", " + s_name + ", " + str(row_num))
work_df = pd.read_excel(f_name, sheet_name=s_name)
# 読込み位置とindexを指定
index = row_num - 1
ret_df = work_df[index:]
if (index >= 1):
col_lists = work_df.iloc[(index-1)]
ret_df.columns = col_lists
return ret_df
test.py
# 階層は . で表す
import hapy_mod.ham as hapy
in_file = 'myリスト_0.xlsx'
in_sheet1 = 'リスト'
df1 = hapy.get_df_from_excel(in_file, in_sheet1, 4)