0
点赞
收藏
分享

微信扫一扫

自动检测MultiIndex的维数并全部转化为整数

单调先生 2023-09-21 阅读 50


将pd.MultiIndex.from_tuples(

   [(int(a), int(b)) for a, b in my_df.index],

   names=my_df.index.names

)改写为自动检测MultiIndex的维数并全部转化为整数的函数

import pandas as pd
import numpy as np

# Your original DataFrame
my_df = pd.DataFrame(
    np.add(np.arange(4).reshape(2, 2), 0.1), columns=['col' + str(i) for i in range(2)]
).pivot_table(
    index=['col' + str(i) for i in range(2)]
)

# Convert MultiIndex to integers
my_df.index = pd.MultiIndex.from_tuples(
    [(int(a), int(b)) for a, b in my_df.index],
    names=my_df.index.names
)

print(my_df.index)

import pandas as pd

def convert_multiindex_to_int(multiindex):
    """
    Convert all levels of a MultiIndex to integers.
    
    Parameters:
    multiindex (pd.MultiIndex): MultiIndex to be converted.
    
    Returns:
    pd.MultiIndex: New MultiIndex with all levels converted to integers.
    """
    new_tuples = [tuple(int(item) for item in tup) for tup in multiindex]
    return pd.MultiIndex.from_tuples(new_tuples, names=multiindex.names)

# Your original DataFrame
my_df = pd.DataFrame(
    np.add(np.arange(4).reshape(2, 2), 0.1), columns=['col' + str(i) for i in range(2)]
).pivot_table(
    index=['col' + str(i) for i in range(2)]
)

# Convert MultiIndex to integers using the function
my_df.index = convert_multiindex_to_int(my_df.index)

print(my_df.index)

举报

相关推荐

0 条评论