导入了一系列csv和xls文件,使用文件中的标题.我注意到这些标题不干净,所以当我调用它时,我得到一个错误,返回说没有这样的属性.我想要做的是与此类似的事情;
使用内置函数创建导入标头的列表
currentheaders = list(df.columns.values)
清理那个清单(这是我坚持的部分)
cleanedheaders = str.strip or regex equivalent
将该列表应用为新标题
df.columns = ['cleanedheaders']
Strip在列表上不起作用,正则表达式想要成为一个数据框,列表是否有相同的功能?
解决方法:
紧凑而快捷的方式
df.columns = [c.strip() for c in df.columns.values.tolist()]
如果你想使用DataFrame.rename()那么你实际上需要像这样调用它:
df.rename(columns={c: c.strip() for c in df.columns.values.tolist()}, inplace=True)
或者你当然可以使用紧凑和快速(由MaxU借用):
df.columns = df.columns.str.strip()
Keep in mind none of the above solutions will work if ANY of the column names are in fact not a string.
如果任何列名不是字符串,那么理想情况下你将它们全部转换为字符串,这将起作用:
df.columns = [str(i) for i in df.columns.values.tolist()]
或者如果你不想将列名转换为字符串 – 我希望有一些好的理由 – 那么你必须做以下事情:
df.rename(columns={c: c.strip() for c in df.columns.values.tolist()
if c not in [<list of columns not strings>]}, inplace=True)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。