Можно ли добавить серию панд в список? - PullRequest
0 голосов
/ 25 июня 2019

В последнее время я работаю над проектом, который предсказывает самую оптимальную команду в фэнтезийной премьер-лиге. После успешного анализа различных характеристик и параметров я застрял из-за следующей ошибки «TypeError: 'Series' являются изменяемыми, поэтому их нельзя хэшировать"

Я завершил написание первой части кода, но получил ошибку. Я искал в сети, но не смог найти решение. Одно из решений гласило, что вы не можете добавлять серии в список. Это правда? и каковы возможные решения для того же. Я зашел слишком далеко, я действительно хочу сделать это правильно.

def my_team (budget = 100, star_player_limit = 3, gk = 2, df = 5, mid = 5, fwd = 3 ): # Pass constraints to function
    team = [ ]                          # List of team to be returned
    star_position = [ ]                 # list containing position of starplayer
    star_player_limit = star_player_limit
    budget = budget
    injured = dataset2.loc[(dataset2.loc[:,"Status"] == 'injured'),:] # Keeping a check of injury status
    positions = {"GKP":gk,"DEF":df,"MID":mid,"FWD":fwd}       # Dict accounting for no. of postions left to fill
    for ind in Top_points.index:       # Looping through the dataframe of players
        player = Top_points.loc[ind]   # Row of Dataframe one at a time
        star_position.append(player.Position)    # Checking position of star player
        if len(team) < star_player_limit and player not in injured and budget > player.Cost and positions[player.Position] > 0 and player.Position not in star_position:
            team.append(player)
            budget -= player.Cost
            positions[player.Position] -= 1

    return team

my_team ()

После запуска кода я получил эту ошибку: TypeError: 'Series' objects are mutable, thus they cannot be hashed.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-150-a7d781e901c6> in <module>()
----> 1 my_team()

<ipython-input-149-ec17dbd9b9ba> in my_team(budget, star_player_limit, gk, df, mid, fwd)
      9         player = Top_points.loc[ind]
     10         star_position.append(player.Position)
---> 11         if len(team) < star_player_limit and player not in injured and budget > player.Cost and positions[player.Position] > 0 and player.Position not in star_position:
     12             team.append(player)
     13             budget -= player.Cost

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __contains__(self, key)
   1517     def __contains__(self, key):
   1518         """True if the key is in the info axis"""
-> 1519         return key in self._info_axis
   1520 
   1521     @property

~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in __contains__(self, key)
   2018     @Appender(_index_shared_docs['__contains__'] % _index_doc_kwargs)
   2019     def __contains__(self, key):
-> 2020         hash(key)
   2021         try:
   2022             return key in self._engine

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __hash__(self)
   1487     def __hash__(self):
   1488         raise TypeError('{0!r} objects are mutable, thus they cannot be'
-> 1489                         ' hashed'.format(self.__class__.__name__))
   1490 
   1491     def __iter__(self):

TypeError: 'Series' objects are mutable, thus they cannot be hashed

1 Ответ

0 голосов
/ 25 июня 2019

Рамки панд изменчивы. Из-за этого их нельзя использовать в качестве ключей к диктовке или элементов набора.

Посмотрите на строку 11 в первой трассировке стека. Я переформатировал его, чтобы он читался.

if (len(team) < star_player_limit and
    player not in injured and
    budget > player.Cost and
    positions[player.Position] > 0 and
    player.Position not in star_position):

У нас есть player not in injured предложение здесь. Первый определяется как

player = Top_points.loc[ind] 

Полагаю, его тип Series.

Теперь у нас есть вторая трассировка стека, метода __contains__, которая обрабатывает оператор in. В нем, я полагаю, self равен injured, а key равен player. Действительно, это не может hash(player).

(Это не может быть вторым предложением in, потому что start_position - это простой список Python, а трассировка стека __contains__ от pandas.)

Я бы извлек имя или другой идентификатор из player и искал его в injured; возможно я бы превратил injured в набор имен по пути.

...