Итерация по словарю во фрейме данных и оценка с использованием условия - PullRequest
1 голос
/ 09 апреля 2020

Мой фрейм данных имеет формат:

 id                            text                                    occurrences  

001 Ad sales boost Time Warner profit\n\nQuarterly...   {'argentina': 0, 'australia':
003 Yukos unit buyer faces loan claim\n\nThe owner...   {'argentina': 0, 'australia': 
004 High fuel prices hit BA's profits\n\nBritish A...   {'argentina': 0, 'australia': 
005 Pernod takeover talk lifts Domecq\n\nShares in...   {'argentina': 0, 'australia': 
... ... ... ...
506 Trial begins of Spain's top banker\n\nThe tria...   {'argentina': 0, 'australia': 
507 UK economy ends year with spurt\n\nThe UK econ...   {'argentina': 0, 'australia': 
508 HealthSouth ex-boss goes on trial\n\nThe forme...   {'argentina': 0, 'australia': 
509 Euro firms miss out on optimism\n\nMore than 9...   {'argentina': 0, 'australia': 
510 Lacroix label bought by US firm\n\nLuxury good...   {'argentina': 0, 'australia': 

Я пытаюсь преобразовать столбец dtype из occurrences (количество стран) в словарь, чтобы я мог сделать что-то вроде этого:

for x in df['occurrences']:
    if x.values() >=1:
        df['iscountrymentioned']='True'
    else: df['iscountrymentioned']='False' 

но когда я делаю это:

df['occurrences'].astype(dict) 

Я получаю ошибку:

TypeError: dtype '<class 'dict'>' not understood

Я знаю, что я делать что-то ужасно неправильное здесь, поскольку выполнение этой части кода без преобразования типов дает мне все ложные значения в iscountrymentioned:

for x in df['occurrences']:
    if x.values() >=1:
        df['iscountrymentioned']='True'
    else: df['iscountrymentioned']='False'

Без преобразования типов дает мне

AttributeError: 'str' object has no attribute 'values'

1 Ответ

1 голос
/ 09 апреля 2020

Один из способов решения проблемы: Вы можете использовать Series.apply, чтобы применить пользовательскую функцию func к значениям серии occurrences. В func вы можете использовать json.loads для десериализации значения в серии occurrence до python dict.

import json

def func(s):
    try:
        d = json.loads(s.replace("'", '"'))
        return True if len(d) > 0 else False
    except json.JSONDecodeError:
        return None

df["iscountrymentioned"] = df["occurrences"].apply(func)

Пример результата:

>>> print(df)
  id                                               text                       occurrences  iscountrymentioned
0   1  Ad sales boost Time Warner profit\n\nQuarterly...  {'argentina': 0, 'australia': 1}                True
1   3  Yukos unit buyer faces loan claim\n\nThe owner...  {'argentina': 0, 'australia': 2}                True
2   4  High fuel prices hit BA's profits\n\nBritish A...  {'argentina': 0, 'australia': 3}                True
3   5  Pernod takeover talk lifts Domecq\n\nShares in...  {'argentina': 0, 'australia': 4}                True
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...