2024-09-29 23:20:14 发布
网友
导入了一系列csv和xls文件,使用文件中的头。我注意到这些头并不干净,所以当我调用它们时,会返回一个错误,说没有这样的属性。我想做的是类似的事情
用于创建列表的内置头函数
currentheaders = list(df.columns.values)
干净(我在名单上)
将该列表作为新标题应用
df.columns = ['cleanedheaders']
Strip对列表不起作用,regex希望成为一个数据帧,是否有一个与列表等效的函数?在
此解决方案将删除列表中的所有元素:
list = [' test1', ' test2 '] print [l.strip() for l in list]
结果:
['test1', 'test2']
试试这个:
columns = {c: c.strip() for c in df.columns} # or any cleaning df.rename(columns, inplace=True)
一个紧凑而快速的方法是
df.columns = [c.strip() for c in df.columns.values.tolist()]
如果您想使用DataFrame.rename(),那么您实际上需要这样称呼它:
DataFrame.rename()
或者您当然可以使用同样紧凑和快速(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)
此解决方案将删除列表中的所有元素:
结果:
试试这个:
一个紧凑而快速的方法是
如果您想使用
^{pr2}$DataFrame.rename()
,那么您实际上需要这样称呼它:或者您当然可以使用同样紧凑和快速(MaxU借用的):
如果任何列名不是字符串,那么理想情况下,您可以将它们全部转换为字符串,这将起作用:
或者,如果您不想将列名转换为字符串(我希望是出于某种好的原因),那么您必须执行以下操作:
相关问题 更多 >
编程相关推荐