数据帧搜索和附加

2024-04-19 05:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在数据框中搜索一个值,如果找不到,就把它添加到数据框中。你知道吗

很简单,但是我被困在上面了(python新手)。。。。你知道吗

数据帧只有一个名为“Value”的列。你知道吗

#sort a random position
    randomico = randint(1,tamanhoRestrito)
     #if the random value does not exist in the solution I add it into solution dataframe
    if (solucao.iloc[0] == listaOrdenada.iloc[randomico]):
         solucao.loc[solucao.index.max() + 1] = [listaOrdenada.iloc[randomico]]

我得到的错误是:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Tags: the数据ifvaluepositionrandomsortsolution
1条回答
网友
1楼 · 发布于 2024-04-19 05:32:55

我认为可以通过在条件中添加not.any()来解决错误:

if not (solucao.iloc[0] == listaOrdenada.iloc[randomico]).any():

如果看不到您的数据,就有点难以准确地知道,但是这种替代方法也可以工作,并且在代码方面更有意义。你知道吗

我假设listaOrdenada.iloc[randomico]是一个值。你知道吗

if listaOrdenada.iloc[randomico] not in solucao['value'].values:
    solucao.loc[solucao.index.max() + 1, 'value'] = listaOrdenada.iloc[randomico]

相关问题 更多 >