У меня был фрейм данных, в котором был столбец со списком вложенных словарей, и мне нужно было разбить этот список на несколько столбцов.
Лучшее решение, которое я нашел, - это использовать str.extract так:
df[0].str.extract('date(?P<date>.*?)firstBoxerRating(?P<firstBoxerRating>.*?)firstBoxerWeight(?P<firstBoxerWeight>.*?)judges(?P<JudgeID>.*?)links(?P<Links>.*?)location(?P<location>.*?)metadata(?P<metadata>.*?)numberOfRounds(?P<numberofrounds>.*?)outcome(?P<outcome>.*?)rating(?P<rating>.*?)referee(?P<referee>.*?)secondBoxer(?P<secondBoxer>.*?)secondBoxerLast6(?P<secondBoxerLast6>.*?)secondBoxerRating(?P<secondBoxerRating>.*?)secondBoxerRecord(?P<secondBoxerRecord>.*?)secondBoxerWeight(?P<secondBoxerWeight>.*?)titles(?P<titles>.*?)')
Однако у меня проблема в том, чтобы дать вам больше контекста. Эти данные относятся к боям, в которых участвовал боец, для каждого боя есть информация о первом боксерском поединке, количестве раундов и т. Д. (Каждый столбец, который я создал). Проблема здесь в том, что есть несколько боев для каждого бойца, в некоторых случаях 20, в других случаях до 60.
Использование моего метода str.extract работает на 1 бой, я не уверен, как сделатьон работает для нескольких боев (извлечение одной и той же информации для всех боев
Вот пример моего исходного кадра данных:
[{"date":"0 1 0" firstBoxerRating:[null null] firstBoxerWeight:339.5 judges:[{"id":400902 name:"Jose Cobian" scorecard:[]} {"id":403562 name:"Juan Jose De La Mora" scorecard:[]} {"id":449036 name:"Juan Carlos Pelayo" scorecard:[]}] links:{"bio":1399268 bout:"569119/1399268" event:569119 other:[]} location:"Plaza de Toros Tijuana" metadata:" time: 0:34\n | <span>referee:</span> <a href=\"/en/referee/9782\">Memo Ayon</a><span> | </span><a href=\"/en/judge/400902\">Jose Cobian</a> | <a href=\"/en/judge/403562\">Juan Jose De La Mora</a> | <a href=\"/en/judge/449036\">Juan Carlos Pelayo</a>\n<br>Ruiz debuts\n<br>" numberOfRounds:[null null] outcome:"unknown" rating:null referee:{"id":9782 name:"Memo Ayon"} result:["unknown" nan null] secondBoxer:{"id":null name:null} secondBoxerLast6:[] secondBoxerRating:[null null] secondBoxerRecord:{"draw":null loss:null win:null} secondBoxerWeight:null titles:[]} {"date":"1 10 1" firstBoxerRating:[null null] firstBoxerWeight:227 judges:[] links:{"bio":1428973 bout:"580396/1428973" event:580396 other:[]} location:"Plaza de Toros Calafia Mexicali" metadata:" time: 1:37\n | <span>referee:</span> <a href=\"/en/referee/410749\">Eduardo Perez</a>\n<br>Brantley down 3 times.\n<br>" numberOfRounds:[null null] outcome:"unknown" rating:null referee:{"id":410749 name:"Eduardo Perez"} result:["unknown" nan null] secondBoxer:{"id":null name:null} secondBoxerLast6:[] secondBoxerRating:[null null] secondBoxerRecord:{"draw":null loss:null win:null} secondBoxerWeight:null titles:[]} {"date":"0 3 1" firstBoxerRating:[null null] firstBoxerWeight:null judges:[] links:{"bio":1494245 bout:"595826/1494245" event:595826 other:[]} location:"Gimnasio de Mexicali Mexicali" metadata:null numberOfRounds:[null null] outcome:"unknown" rating:null referee:{"id":null name:null} result:["unknown" nan null] secondBoxer:{"id":null name:null} secondBoxerLast6:[] secondBoxerRating:[null null] secondBoxerRecord:{"draw":null loss:null win:null} secondBoxerWeight:null titles:[]} {"date":"0 1 0" firstBoxerRating:[null null] firstBoxerWeight:200 judges:[] links:{"bio":1496079 bout:"594726/1496079" event:594726 other:[]} location:"Gaylord Hotel Grapevine" metadata:" time: 1:55\n | <span>referee:</span> <a href=\"/en/referee/401404\">Robert Chapa</a>\n<br>" numberOfRounds:[null null] outcome:"unknown" rating:null referee:{"id":401404 name:"Robert Chapa"} result:["unknown" nan null] secondBoxer:{"id":null name:null} secondBoxerLast6:[] secondBoxerRating:[null null] secondBoxerRecord:{"draw":null loss:null win:null} secondBoxerWeight:null titles:[]} {"date":"1 3 0" firstBoxerRating:[null null] firstBoxerWeight:233 judges:[] links:{"bio":1545483 bout:"608654/1545483" event:608654 other:[]} location:"Silverton Casino & Lodge Las Vegas" metadata:" time: 1:06\n | <span>referee:</span> <a href=\"/en/referee/401026\">Tony Weeks</a>\n<br>" numberOfRounds:[null null] outcome:"unknown" rating:null referee:{"id":401026 name:"Tony Weeks"} result:["unknown" nan null] secondBoxer:{"id":null name:null} secondBoxerLast6:[] secondBoxerRating:[null null] secondBoxerRecord:{"draw":null loss:null win:null} secondBoxerWeight:null titles:[]} {"date":"2 2 0"
Эта информация реплицируется для нескольких боев
Я попытался разбить данные на разные столбцы для каждого боя, используя дату в качестве точки разделения
df_two = pd.DataFrame(df[0].str.replace('date','dateday'))
df_three = pd.DataFrame(df_two[0].str.split('date',expand=True))
, которая дает мне столбец для каждого боя, а затем перебирает каждый столбец и применяет мой str.extractrule:
def func(df,col):
return df[col].str.extract('day(?P<day>.*?)firstBoxerRating(?P<firstBoxerRating>.*?)firstBoxerWeight(?P<firstBoxerWeight>.*?)judges(?P<JudgeID>.*?)links(?P<Links>.*?)location(?P<location>.*?)metadata(?P<metadata>.*?)numberOfRounds(?P<numberofrounds>.*?)outcome(?P<outcome>.*?)rating(?P<rating>.*?)referee(?P<referee>.*?)secondBoxer(?P<secondBoxer>.*?)secondBoxerLast6(?P<secondBoxerLast6>.*?)secondBoxerRating(?P<secondBoxerRating>.*?)secondBoxerRecord(?P<secondBoxerRecord>.*?)secondBoxerWeight(?P<secondBoxerWeight>.*?)titles(?P<titles>.*?)')
df_three[['date', 'firstBoxerRating', 'firstBoxerWeight', 'JudgeID', 'Links',
'location', 'metadata', 'numberofrounds', 'outcome', 'rating',
'referee', 'secondBoxer', 'secondBoxerLast6', 'secondBoxerRating',
'secondBoxerRecord', 'secondBoxerWeight', 'titles']] = func(df_three,1).drop([1])
for i in range(len(df_three.columns)):
df_three[['date'+str(i), 'firstBoxerRating'+str(i), 'firstBoxerWeight'+str(i), 'JudgeID'+str(i), 'Links'+str(i),
'location'+str(i), 'metadata'+str(i), 'numberofrounds'+str(i), 'outcome'+str(i), 'rating'+str(i),
'referee'+str(i), 'secondBoxer'+str(i), 'secondBoxerLast6'+str(i), 'secondBoxerRating'+str(i),
'secondBoxerRecord'+str(i), 'secondBoxerWeight'+str(i), 'titles'+str(i)]] = func(df_three,i).drop([i])
Однако это возвращает ошибку:
KeyError: '[6] не найден по оси'
Несмотря на то, чтовсе столбцы имеют имена от 0 до 44