替换列表中的值 - Python
Replace values in list - 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
有人能帮帮我吗?
您正在尝试混合和匹配两种不同类型的迭代(基于索引和基于值)。您可以更简单地执行此操作作为列表理解,遍历值并从替换项构建新列表:
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
第一种方法(列表理解)是我推荐的方法。
我正在尝试重构以下代码:
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
有人能帮帮我吗?
您正在尝试混合和匹配两种不同类型的迭代(基于索引和基于值)。您可以更简单地执行此操作作为列表理解,遍历值并从替换项构建新列表:
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
第一种方法(列表理解)是我推荐的方法。