0

Considering the following list made up of sub-lists as elements, I need to create a pandas dataframe

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]

The desired output is as following, with the first argument being converted to the column name in the dataframe.

   tom  nick  juli
0   10    15    14

Is there a way by which this output can be achieved?

Best Regards.

3 Answers 3

2

Use dictionary comprehension and pass to DataFrame constructor:

print ({x[0]: x[1:] for x in data})
{'tom': [10], 'nick': [15], 'juli': [14]}

df = pd.DataFrame({x[0]: x[1:] for x in data})
print (df)
   tom  nick  juli
0   10    15    14
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @jezrael this works exactly as needed. You've helped me out here again, can't thank you enough.
2

You could also use dict + extended iterable unpacking:

import pandas as pd

data = [['tom', 10], ['nick', 15], ['juli', 14]]

result = pd.DataFrame(dict((column, values) for column, *values in data))

print(result)

Output

   tom  nick  juli
0   10    15    14

Comments

2

We also do:

pd.DataFrame(data).set_index(0).T

0  tom  nick  juli
1   10    15    14

1 Comment

Thanks @ansev This is also a solution !

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.