1

I have a pandas dataframe that I created from a response of an API request.One of the fields in my dataframe contains a list containing a unique dictionary like this : my dataframe

I would like to create a new dataframe from this dictionary I have tried several methods but I have not succeeded, an example of what I tried extracting the dictionary to put them in a list and create a dataframe from it:

traking = df['traking'].tolist()
temp_list = []
for li in traking:
    temp_list.append(li[0])

I receive IndexError: list index out of range
but if I print(li[0]) I have my dictionary that appears, I'm a bit lost

1 Answers1

0

I tried to replicate your dataframe and modified the answer based on the comment you put below.

import pandas as pd

lists = [[[{'key1': 'value1', 'key2': 'value2'}]],] * 10

df = pd.DataFrame(lists, columns=['traking'])

traking = df['traking'].tolist()
keys = list(traking[0][0].keys())
print(keys)

temp_list = []
for li in traking:
    values = [li[0][key] for key in keys]
    temp_list.append(values)
    
# Output:
# keys = ['key1', 'key2']
# temp_list = [['value1', 'value2'], 
#              ['value1', 'value2'],
#              ...,
#              ['value1', 'value2']]

This should provide the expected output

scandav
  • 749
  • 1
  • 7
  • 21
  • i would like an Output like this: ` # foo bar etc # 0 value value value # 1 value value value ` – PetitGuigui Oct 15 '21 at 11:54
  • I'm in trouble with the opposite problem (https://stackoverflow.com/questions/69573318/how-to-create-a-submultiple-level-list). Could please anyone help me? – 12666727b9 Oct 15 '21 at 11:58
  • See updated answer – scandav Oct 15 '21 at 12:04
  • i have same error in my my output 'Index out of range' and however my list is correct. When I try to print li[0], it works but when I assign them, I get an "index out of range" error message. for more precision when I type(traking) I have list and when I type(li) I have – PetitGuigui Oct 15 '21 at 12:24
  • Try to print the row index you get the error at and check whether it is a list or not. It looks to me that you're trying to access index 0 of an empty list, – scandav Oct 15 '21 at 12:28