Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert tuple of tuples to pandas.DataFrame in Python?

No offence, if the questions is too basic. Let me know if you need more information.

I am looking for an idea to convert square-form tuple of tuples to pandas.DataFrame in a clean/efficient/pythonic way, i.e. from

s =((1,0,0,0,),(2,3,0,0,),(4,5,6,0,),(7,8,9,10,)) 

to pandas.DataFrame like

   1  2  3   4 1  1  0  0   0 2  2  3  0   0 3  4  5  6   0 4  7  8  9  10 

Naturally, this list can grow with more zeros appended in the upper-triangular (if we think of s as a tuple of rows).

DataFrame(t) seems to fail.

like image 611
Oleg Melnikov Avatar asked Nov 13 '15 19:11

Oleg Melnikov


People also ask

Can tuple of tuples be used to create DataFrame?

We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use.

Can we create pandas DataFrame using dictionary of tuples?

So we can use strings, numbers (int or float), or tuples as keys. Values can be of any type. We can also pass a dictionary to the dataframe function. The keys will be column names and the values will form the columns.

How do you convert a tuple to a list of tuples in Python?

To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.

How do you convert a tuple in Python?

1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.


1 Answers

import pandas as pd  s = ((1,0,0,0,),(2,3,0,0,),(4,5,6,0,),(7,8,9,10,))  print pd.DataFrame(list(s))  #    0  1  2   3 # 0  1  0  0   0 # 1  2  3  0   0 # 2  4  5  6   0 # 3  7  8  9  10  print pd.DataFrame(list(s), columns=[1,2,3,4], index=[1,2,3,4])    #    1  2  3   4 # 1  1  0  0   0 # 2  2  3  0   0 # 3  4  5  6   0 # 4  7  8  9  10 
like image 159
furas Avatar answered Oct 03 '22 11:10

furas