2017-04-19 41 views
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, 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: Buffer has wrong number of dimensions (expected 1, got 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 

与所需的具体指标和列名自动创建列和行。 但是,我无法替换我试图找到的某些值。

+0

到底为什么你不能从数据帧之内更换它们呢? –

+0

,这似乎是'pandas'完全可行的东西 –

+0

是啊!我知道如何在熊猫中做到这一点,但我想在列表中尝试它 – aze45sq6d

回答

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.') 

(我没有大熊猫现在所以这个例子使用类型的字典列表,而不是) 。

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

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') 
+0

谢谢!该功能就像一个魅力! – aze45sq6d

相关问题