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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With