python - 根据索引从列表项中删除引号
问题描述
我有一个列表格式的二维 numpy 数组。这是片段
[['0', '05:15', '07:12', '315', '432', '117', '901', '0'], ['1', '05:25', '07:24', '325', '444', '119', '902', '0'], ['2', '06:24', '07:37', '384', '457', '73', '903', '901'], ['3', '07:12', '07:49', '432', '469', '37', '901', '902'], ['4', '07:12', '08:13', '433', '493', '61', '903', '901']]
我用sample1.to_numpy().tolist()
where sample1 是我的 DataFrame。
我想要这个格式的列表。
[[0, '04:30', '04:53', 270, 293, 23],
[1, '04:46', '04:56', 286, 296, 10]]
基本上,我需要从我尝试过的列表中所有行的选定元素索引中删除引号strip()
,replace()
但保持不变。有人可以分享实现这一目标的方法。
解决方案
像这样使用列表理解:
>>> [[int(s) if s.isdigit() else s for s in l] for l in sample1]
[[0, '05:15', '07:12', 315, 432, 117, 901, 0],
[1, '05:25', '07:24', 325, 444, 119, 902, 0],
[2, '06:24', '07:37', 384, 457, 73, 903, 901],
[3, '07:12', '07:49', 432, 469, 37, 901, 902],
[4, '07:12', '08:13', 433, 493, 61, 903, 901]]
如果您希望有float
值并希望转换为浮动:
>>> [[float(s) if s.isnumeric() else s for s in l] for l in sample1]
[[0.0, '05:15', '07:12', 315.0, 432.0, 117.0, 901.0, 0.0],
[1.0, '05:25', '07:24', 325.0, 444.0, 119.0, 902.0, 0.0],
[2.0, '06:24', '07:37', 384.0, 457.0, 73.0, 903.0, 901.0],
[3.0, '07:12', '07:49', 432.0, 469.0, 37.0, 901.0, 902.0],
[4.0, '07:12', '08:13', 433.0, 493.0, 61.0, 903.0, 901.0]]
编辑:
如果您只想在某些索引处转换元素(例如,0th 4th 和 5th):
>>> [[int(s) if i in [0, 4, 5] else s for i, s in enumerate(l)] for l in sample1]
[[0, '05:15', '07:12', '315', 432, 117, '901', '0'],
[1, '05:25', '07:24', '325', 444, 119, '902', '0'],
[2, '06:24', '07:37', '384', 457, 73, '903', '901'],
[3, '07:12', '07:49', '432', 469, 37, '901', '902'],
[4, '07:12', '08:13', '433', 493, 61, '903', '901']]
推荐阅读
- node.js - 大的post请求使Nodejs服务器堆内存不足
- laravel - 不能使用 Conekta\Object 作为对象,因为“对象”是一个特殊的类名
- java - Gradle 参与 Android 构建过程
- azure-devops - 如何在多个目录中模式匹配不同的文件
- ruby-on-rails - 在不重启服务的情况下刷新 Ruby on Rails DNS 缓存
- css - 如何将相同的样式应用于具有相同父路径的不同深层选择器
- php - 需要帮助将 div 样式添加到 php echo 语句
- python-3.x - Discord.py 重写 - YoutubeDL 播放音乐的来源是什么?
- c# - 如何从 IExceptionFilter.OnException() 返回源视图
- ruby-on-rails - 什么时候在 sidekiq 中创建工作和子工作的正确策略是什么?