1

I have the list

[[(1, 1, {(58091,)}, ('roma',))], [(11, 11, {(97042,)}, ('lecco',))], [(3, 3, {(97068,)}, ('pescate',))]]

I would like to save data in 4 columns as following

id one   id two   id       place
1           1     58091     roma
11         11     97042     lecco
3           3     97068     pescate

what I did

your_list = [[(1, 1, {(58091,)}, ('roma',))], [(11, 11, {(97042,)}, ('lecco',))], [(3, 3, {(97068,)}, ('pescate',))]]
df = DataFrame (your_list,columns=['id one','id two','id','place'])

but it is not working I believe it is due to the brackets but I do not know how to deal with them

4
  • From what I have seen, your list looks incomplete to me: {(58091,)}, ('roma',)), why are there extra , when there is no other value? Commented May 27, 2021 at 8:06
  • I'd suggest to ensure your input data (your_list) is of proper format before turning it into a pd.DataFrame. Commented May 27, 2021 at 8:06
  • @Sujay That's a tuple with one element. Commented May 27, 2021 at 8:29
  • any hint how to clean the data input? Commented May 27, 2021 at 8:33

1 Answer 1

2

With this particular data format, you can flatten the list of lists using a custom function with list comprehension:

data = [[(1, 1, {(58091,)}, ('roma',))], [(11, 11, {(97042,)}, ('lecco',))], [(3, 3, {(97068,)}, ('pescate',))]]

def unnest(s):
    if isinstance(s, str) or isinstance(s, int):
        return s
    else:
        for i in s:
            return unnest(i)

print (pd.DataFrame([[unnest(z) for z in y] for x in data for y in x],
                    columns=['id one','id two','id','place']))

   id one  id two     id    place
0       1       1  58091     roma
1      11      11  97042    lecco
2       3       3  97068  pescate
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.