python改变变量名称_Python批处理更改变量名(列名字符串替换),读取同一类型的多个文件并将它们合并,python,批量,名列...

# 替换某些变量名中的 某部分 字符串

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值