1
import pandas as pd
input_thing = [
    [{'foo': 1, 'bar': 'a', }], 
    [{'foo': 2, 'bar': 'b', }],
]
print(input_thing)

How can I get a nice pandas dataframe out of the data displayed above? I.e. that the columns foo and bar are nicely displayed on the outside

 pd.DataFrame(input_thing)

Only will generate a dataframe with a single column 0

The desired output would be:

pd.concat([
    pd.DataFrame(input_thing[0]),
    pd.DataFrame(input_thing[1])
])

2 Answers 2

2

If every sublist in input_thing has one element:

df = pd.DataFrame([i[0] for i in input_thing])
print(df)

Prints:

   foo bar
0    1   a
1    2   b

EDIT:

df = pd.DataFrame(input_thing)
print(df[0].apply(pd.Series))

Prints:

   foo bar
0    1   a
1    2   b
Sign up to request clarification or add additional context in comments.

6 Comments

Sure - but is there also a vectorized way?
@GeorgHeiler See my edit. I added a version with pd.Series
I'm certain df.apply(pd.Series) is very slow compared to list comprehension as it builds Series object for each item in the list which adds way too much overhead. Your better off using list comprehension.
@Ch3steR You beat me to it :)... I was going to do some timeit test.
@AndrejKesely haha :P You could also do pd.DataFrame(chain.from_iterable(input_thing)) too. Anyways nice one.
|
0

Just replace your pd.concat with a for loop:

import pandas as pd
input_thing = [
[{'foo': 1, 'bar': 'a', }], 
[{'foo': 2, 'bar': 'b', }],
]
df = pd.DataFrame([i[0] for i in input_thing])
print(df)

Then it will get what you want:

    foo bar
0    1   a
1    2   b

This is what you desire.

2 Comments

It's the same as andrej's answer. Duplicate answers don't help the community. If you have an alternate answer you can add that.
I just want to emphasize to use a loop to replace the pd.concat.

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.