替换列表中的特定多个值

时间:2017-04-19 14:40:21

标签: python list replace

在将此标记为重复之前,请仔细阅读。

我正在尝试查找并替换列表中的某个值。 该列表如下所示:

[score                      405.738
 start    2015-11-10 06:04:00+00:00
 stop     2015-11-10 06:55:00+00:00
 Name: 23, dtype: object, score                      401.088
 start    2015-11-10 05:41:00+00:00
 stop     2015-11-10 06:32:00+00:00
 Name: 0, dtype: object]

我们说这是list_v。 打印list_v [0]给出:

score                      405.738
start    2015-11-10 06:04:00+00:00
stop     2015-11-10 06:55:00+00:00
Name: 23, dtype: object

我想要的是类似这个:

if current_value['score'] in list_v:
    ind = list_v.index(current_value['score'])

然后,我会简单地覆盖索引中的任何内容。

我收到此错误:

  

ValueError:缓冲区的维数错误(预期为1,得0)

如果我的列表看起来像这样

[405.73842646140832,
 Timestamp('2015-11-10 06:04:00+0000', tz='UTC'),
 Timestamp('2015-11-10 06:55:00+0000', tz='UTC'),
 401.0883140755235,
 Timestamp('2015-11-10 05:41:00+0000', tz='UTC'),
 Timestamp('2015-11-10 06:32:00+0000', tz='UTC')]

然而,它没有,我不希望它,因为我想稍后将其转换为数据帧。 将第一个转换为数据帧可以提供我想要的内容:

score   start   stop
23  405.738426  2015-11-10 06:04:00+00:00   2015-11-10 06:55:00+00:00
0   401.088314  2015-11-10 05:41:00+00:00   2015-11-10 06:32:00+00:00

自动创建具有所需精确索引和列名称的列和行。 但后来我无法替换我想要找到的某些值。

1 个答案:

答案 0 :(得分:1)

我想到的两个选项是将分数复制到单独的列表中,或者编写一个函数来搜索DataFrame中的分数。

如果您的数据不是太大,复制分数可能会更清晰一些:

data = [{
    'name': 'First Thing',
    'score': 1
}, {
    'name': 'Second Thing',
    'score': 2
}]

scores = [d['score'] for d in data]

# Tested with a value that is a valid score and one that isn't.
current_value = {'score': 1}
# current_value = {'score': -1}

if current_value['score'] in scores:
    ind = scores.index(current_value['score'])
    print('Index: %d' % ind)
    print(data[ind])
else:
    print('Score not found.')

(我现在没有熊猫,所以这个例子使用带有dicts的列表)。

或者,您可以使用自定义搜索功能:

def find_score(data):
    for ind, d in enumerate(data):
        if current_value['score'] == d['score']:
            return ind, d
    return None, None

ind, d = find_score(data)
if ind is not None:
    print('Index: %d' % ind)
    print(d)
else:
    print('Score not found')