在数据框中找不到索引

时间:2017-08-23 07:47:50

标签: python pandas numpy

我正在尝试用简单的q学习算法来解决强化学习问题。 如果代理人还不知道,我必须在我的表中添加一个新状态。 我遇到的问题是,当我学习新状态时,我有以下错误:'None of [x] are in the [index]'

我做了一些测试代码,以了解发生了什么,并在遇到问题时解决问题,但我找不到解决方案。

这是我的代码:

import pandas as pd
import numpy as np
import random

actions = [0, 1]
obs = (0)


q_table = pd.DataFrame(columns=actions)


def check_state_exist(state):
    global q_table
    if state not in q_table.index:
        # append new state to q table
        q_table = q_table.append(
            pd.Series(
                [0]*len(actions),
                index=q_table.columns,
                name=state,
            )
        )
def choose_action(state):
    global actions
    check_state_exist(state)
    # action selection
    if np.random.uniform() < 0.9:
        # choose best action
        state_action = q_table.loc[state, :]
        state_action = state_action.reindex(np.random.permutation(state_action.index))     # some actions have same value
        action = np.argmax(state_action)
    else:
        # choose random action
        action = np.random.choice(actions)
    return action


for i in range(50):

    rand = random.randrange(100)
    if rand == 1:
        obs = 'rare'
    else: 
        obs = [rand, random.randrange(10)]
        obs = tuple(obs)

    choose_action(obs)

'[(56,5)]都不在[index]'

print(q_table)

         0  1
(56, 5)  0  0

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

当您使用元组作为索引时,pandas将自动表现为多索引。如果要在独奏级别索引中使用(56,5)进行索引,您可能需要尝试类似q_table.loc[[(56,5)]]的内容(不确定它是否有效)。否则,因为在Q-learning中有意义,您可以尝试使用多索引。

答案 1 :(得分:0)

嗯,经过几个小时的测试,我终于解决了问题。我没有使用元组,而是使用了一个字符串。 因为.loc试图找到索引的编号,而不是索引的名称,所以我发现了它。