首页 > 解决方案 > 根据索引从列表项中删除引号

问题描述

我有一个列表格式的二维 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()但保持不变。有人可以分享实现这一目标的方法。

标签: pythonlist

解决方案


像这样使用列表理解:

>>> [[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']]

推荐阅读