简体   繁体   中英

Python / Pandas - how to define the dtype of a column when Dataframe is a multi-index DataFrame?

Let say I have following multi-index DataFrame.

import pandas as pd
row_axis = pd.MultiIndex(levels=[[],[]], codes=[[],[]], names=['Data', 'Period'])
column_axis = [['Index','Index', 'Data'],['First','Last','Min']]
MD = pd.DataFrame(index=row_axis, columns=column_axis)

Later on, when filling a row, I can have values like this.

MD.loc[('hi','5m'),:]=[5,10,'hello']

Checking dtypes, it tells me:

In [17]:MD.dtypes
Out[17]: 
Index  First    object
       Last     object
Data   Min      object
dtype: object

How can I convert the type in the first column ('Index', 'First')?

Trying:

MD = MD.astype({'(Index, First)' : int)

Gives:

KeyError: 'Only a column name can be used for the key in a dtype mappings argument.'

Any help is appreciated, thanks!

In your case

MD = MD.astype({('Index', 'First') : int})
MD.dtypes
Out[53]: 
Index  First     int32
       Last      int64
Data   Min      object
dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM