Can't create pandas DataFrame with MultiIndex columns from dicts with tuples as columns

Viewed 103

I have this Python data structure:

a = [
    {
        ('Temperature', 'C'): 25,
        ('Temperature', 'F'): 77
    },
    {
        ('Temperature', 'C'): 30,
        ('Temperature', 'F'): 86
    }
]

I try to convert this data structure to a tab separated string like this, having 2 rows for header:

Temperature Temperature
C   F
25  77
30  86

In order to do this, I try to convert this data structure first into a DataFrame with MultiIndex columns. But I cannot do it using DataFrame.from_records(a) method because it returns a single index column with tuples as the names. How can I achieve MultiIndex columns instead?

By the way, I can do the reverse. When I have a tab separated file like above, I can read it with:

a_as_dataframe = pd.read_csv(r"C:\my_tab_separated_file.tsv", sep="\t", header=[0, 1])

Then convert it to records like this:

a = a_as_dataframe.to_dict("records")

What I want to achieve is the reverse of this.

1 Answers

How about using MultiIndex.from_tuples

df = pd.DataFrame(a)
df.columns = pd.MultiIndex.from_tuples(df.columns)

df is now:

  Temperature
            C   F
0          25  77
1          30  86
>>> df.equals(a_as_dataframe)
True
Related