# 替換某些變量名中的 某部分 字符串
def re_columns(dt, substr, newstr, ls):
"""
Parameters
----------
dt : datasets
substr : str
string that will be replaced.
newstr : str
string that will replace substr.
ls : list
the column index in the datasets, like [0, 1, 3].
"""
dt.columns = dt.columns.map(lambda x: x.replace(substr, newstr))
#dt.iloc[:, ls] = dt.iloc[:, ls].astype(str) # 轉換變量的數據類型
return dt
# 讀取多個同類型文件,併合並;文件名有相同的前綴或後綴等,便於glob自動識別文件名,過濾無效文件名
import glob
NewFile = pd.DataFrame()
# 文件名以 DailyReport 開始
for file_r in glob.glob("DailyReport*.csv"):
data_r = pd.read_csv(file_r)
# 更改列名,使用到上述自定義函數re_columns,如不需要可註釋
data_r = re_columns(data_r, 'str1', 'newstr1', [0,1,2,3])
data_r = re_columns(data_r, 'str2', 'newstr2', [0,1,2,3]) # 更改列名
NewFile = NewFile.append(data_r)