отделяйте dict от списка в столбце данных pandas в разные столбцы данных - PullRequest
0 голосов
/ 09 ноября 2019
[{
"name":"game_time",
"type":"int",
"info":"millisecond count since start of game"
},
{
"name":"round",
"type":"int",
"info":"number of the current round when the even takes place or 0 if no round"
}]

моя попытка:

характеристики: Фрейм данных, содержащий столбец args, образец файла прикреплен ниже

specs['args'].apply(lambda x : x.split('},{')).to_frame()['args'].apply(pd.Series).apply(lambda x : x.str[2:])
specs['args'].apply(pd.Series)

файл образца

Ответы [ 2 ]

1 голос
/ 09 ноября 2019

Я надеюсь, что ast поможет вам в этом случае. Вот решение

одна версия результата

import pandas as pd
from ast import literal_eval

df = pd.read_csv('test_.csv', header = None)
df

Out[1]:

           0
    0   [{"name":"game_time","type":"int","info":"mill...
    1   [{"name":"game_time","type":"int","info":"mill...
    2   [{"name":"game_time","type":"int","info":"mill...
    3   [{"name":"game_time","type":"int","info":"mill..

lst = [m for s in df[0] for m in literal_eval(s)]
lst

Out[2]:

[{'name': 'game_time',
  'type': 'int',
  'info': 'millisecond count since start of game'},
 {'name': 'round',
  'type': 'int',
  'info': 'number of the current round when the event takes place or 0  if no round'},
 {'name': 'level',
  'type': 'int',
  'info': 'number of the current level when the event takes place or 0     if no level'},
 {'name': 'description',.......


pd.DataFrame.from_dict(lst)

Out[3]:

                                                     info   name        type
    0   millisecond count since start of game               game_time   int
    1   number of the current round when the event tak...   round       int
    2   number of the current level when the event tak...   level       int
    3   the text or description of the instruction          description string
    ........

это ваш желаемый результат?

другаяверсия результата

, если вы хотите получить такой же вывод, как в вашем коде, вот пример

lst1 = [literal_eval(s) for s in df[0]]
pd.DataFrame(lst1)
0 голосов
/ 09 ноября 2019

Просто используйте конструктор DataFrame

data = [{
"name":"game_time",
"type":"int",
"info":"millisecond count since start of game"
},
{
"name":"round",
"type":"int",
"info":"number of the current round when the even takes place or 0 if no round"
}]

print(pd.DataFrame(data))

out:

                                                info       name type
0              millisecond count since start of game  game_time  int
1  number of the current round when the even take...      round  int
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...