python - 在给定列的一行中删除逗号的其他方法
问题描述
喜欢
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
如何解决上述问题?
解决方案
您的代码在不包含逗号的字符串上失败,这意味着列表只有一个元素:整个字符串。
>>> '1.49'.split(',')
['1.49']
要修复它,只需删除逗号str.replace
:
i = i.replace(',', '')
例如:
>>> '1.49'.replace(',', '')
'1.49'
>>> '4.1,204'.replace(',', '')
'4.1204'
推荐阅读
- typescript - 获取错误 TS1241:作为表达式调用时无法解析方法装饰器的签名
- implementation - VC2015 中的 FMI 实现
- spring - Spring Boot 不从模板加载视图
- coreml - 从后台到前台运行 coreml 批量预测时崩溃
- html - HTML 输入占位符,第一个字母 CSS 更改不适用于更新的浏览器
- c# - 延迟 IQueryable 执行的事件
- excel - Delete Entire Row 不删除行,代码继续运行,没有错误
- javascript - 如何使用一个 jquery 在同一页面中制作多个阅读更多按钮?
- php - 自定义 php 包中的命名空间问题,无法执行“使用 joelwmale/RSSFeedPHP”
- python - 有没有办法使用 pyspark 动态创建模式信息,而不是在输出 jsonfile 中转义字符?