提问者:小点点

替换列表中的值-Python


我正在尝试重构以下代码:

labels = list(df.columns)
labels[0] = labels[0].replace(' ', '_')
labels[1] = labels[1].replace(' ', '_')
labels[2] = labels[2].replace(' ', '_')
labels[3] = labels[3].replace(' ', '_')
labels[5] = labels[5].replace(' ', '_')
labels[6] = labels[6].replace(' ', '_')
df.columns = labels

df.head()

重构代码的尝试如下所示:

labels = list(df.columns)
n=0
for n in list(df.columns):
    labels[n].replace(' ','_')
    n = n+1

df.columns = labels
df.head()

但我收到一个错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-13-63763510d35a> in <module>()
      2 n=0
      3 for n in list(df.columns):
----> 4     labels[n].replace(' ','_')
      5     n = n+1
      6 

TypeError: list indices must be integers or slices, not str

谁能帮帮我吗?


共1个答案

匿名用户

您正在尝试混合和匹配两种不同类型的迭代(基于索引和基于值)。 您可以更简单地将其作为列表理解,迭代值并从替换中构建一个新列表:

df.columns = [n.replace(' ', '_') for n in list(df.columns)]

如果要通过迭代列表的索引来修改每个元素,则如下所示:

labels = list(df.columns)
for n in range(len(labels)):
    labels[n] = labels[n].replace(' ','_')
df.columns = labels

不需要递增n,因为for.。。in range已经为您提供了递增的n值。 如果您正在编写while循环,则只需要自己管理n的值:

labels = list(df.columns)
n = 0
while n < len(labels):
    labels[n] = labels[n].replace(' ','_')
    n = n + 1
df.columns = labels

第一种方法(列表理解)是我推荐的。