Pandas: Adding MultiIndex to a 1-row DataFrame

I have a small data frame, for example:

enter image description here

and a tuple such as: (Timestamp('2009-02-27 09:45:00'), 'bloomberg', 'Chicago PMI')

I would like to create a multi-index in a DataFrame so that it reads something like:

enter image description here

When trying to build a MultiIndex:
MI=pd.MultiIndex(index, (0,0,0))
 I encounter the following error:
TypeError: Index(...) must be called with a collection of some kind, Timestamp('2009-02-27 09:45:00') was passed
 what does not seem to allow a 1-line DataFrame with MultiIndex?

I repeat mysql db to get these 1 rows of DataFrame to compose them. Trying to use the argument keysfrom the concat command, create another set of problems, so hopefully you can create this 1 row DataFrame with MultiIndex

The following is the data to recover a data frame:
import pandas as pd from pandas import Timestamp dikt={'actual': {0: '34.2'}, 'previous': {0: '33.3'}, 'forecast': {0: '33.0'}, 'importance': {0: 81.300799999999995}} pd.DataFrame(dikt, columns=['actual', 'forecast', 'previous', 'importance'])

+4
source share
2

df = pd.DataFrame(
    [[34.2, 33., 33.3, 81.3008]],
    columns=['actual', 'forecast', 'previous', 'importance'])

tup = (pd.Timestamp('2009-02-27 09:45:00'), 'bloomberg', 'Chicago PMI')

pd.MultiIndex

df.index = pd.MultiIndex.from_tuples([tup])
df

enter image description here

df.index = [[i] for i in tup]
df

enter image description here

, rename
, TUPLE

df.rename(index=lambda x: tup)

enter image description here

+4
df.index = pd.MultiIndex(
    [[Timestamp('2009-02-27 09:45:00')], 
     ['bloomberg'], ['Chicago PMI']], [[0], [0], [0]], names = [
        'timestamp', 'agency', 'item'])
print(df)
                                         actual forecast previous  importance
timestamp           agency    item                                            
2009-02-27 09:45:00 bloomberg Chicago PMI   34.2     33.0     33.3     81.3008
+1

Source: https://habr.com/ru/post/1668144/


All Articles