首页 > 解决方案 > 在给定列的一行中删除逗号的其他方法

问题描述

喜欢

1.49
2.312
3.499
4.1,204
5.3,001
6.2,500

在上列Likes中有六行,我想删除第 4、5 和 6 行中的逗号。我尝试使用下面提到的代码删除逗号:

b=[]
c=train['Likes']
for i in c:
    d=i.split(',')
    e=d[0]+d[1]
    b.append(e)
train['likes']=b

运行上面的代码后,我得到了错误:

 IndexError                                Traceback (most recent call last)
<ipython-input-41-aaaf683b8888> in <module>
      3 for i in c:
      4     d=i.split(',')
----> 5     e=d[0]+d[1]
      6     b.append(e)
      7     #b.append(f)

IndexError: list index out of range

如何解决上述问题?

标签: pythonlist

解决方案


您的代码在不包含逗号的字符串上失败,这意味着列表只有一个元素:整个字符串。

>>> '1.49'.split(',')
['1.49']

要修复它,只需删除逗号str.replace

i = i.replace(',', '')

例如:

>>> '1.49'.replace(',', '')
'1.49'
>>> '4.1,204'.replace(',', '')
'4.1204'

推荐阅读