要创建以 MultiIndex 的级别作为列的 DataFrame,请使用. 该指标参数设置假以避免将返回数据框的索引multiIndex.to_frame()
首先,导入所需的库 -
import pandas as pd
MultiIndex 是 Pandas 对象的多级或分层索引对象。创建数组 -
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
“names”参数设置每个索引级别的名称。将from_arrays()被用来创建一个多指标-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
使用to_frame(). 使用“index”参数并将其设置为“False”以避免设置返回的DataFrame的索引 -
dataFrame = multiIndex.to_frame(index=False)
以下是代码 -
import pandas as pd # MultiIndex is a multi-level, or hierarchical, index object for pandas objects # Create arrays arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']] # The "names" parameter sets the names for each of the index levels # The from_arrays() is used to create a MultiIndex multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) # display the MultiIndex print("The Multi-index...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in Multi-index...\n",multiIndex.levels) # Create a DataFrame with the levels of the MultiIndex as columns using to_frame() # Use the "index" 参数并将其设置为 "False" to avoid setting the index of the returned #DataFrame dataFrame = multiIndex.to_frame(index=False) # Return the DataFrame print("\nThe DataFrame...\n",dataFrame)输出结果
这将产生以下输出 -
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], names=['ranks', 'student']) The levels in Multi-index... [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']] The DataFrame... ranks student 0 1 John 1 2 Tim 2 3 Jacob 3 4 Chris