Python - 在 Pandas DataFrame 中堆叠多级列
要堆叠多级列,请使用stack()方法。首先,导入所需的库-
import pandas as pd
创建一个多级列-
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),('Maths', 'Applied Mathematics')])
现在,创建一个DataFrame并设置我们上面设置的多级列-
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)
堆叠多级列-
dataframe.stack()
示例
以下是完整的代码-
import pandas as pd #multi-levelcolumns items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'), ('Maths', 'Applied Mathematics')]) #creatingaDataFrame dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items) #DataFrame print"DataFrame...\n",dataFrame #stackmulti-levelcolumns print"\nStacking...\n",dataFrame.stack()输出结果
这将产生以下输出-
DataFrame... Maths Mental Maths Discrete Mathematics Applied Mathematics John 67 86 78 Tom 56 92 97 Henry 92 95 91 Stacking... Maths John Applied Mathematics 78 Discrete Mathematics 86 Mental Maths 67 Tom Applied Mathematics 97 Discrete Mathematics 92 Mental Maths 56 Henry Applied Mathematics 91 Discrete Mathematics 95 Mental Maths 92