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-level columns
items = pd.MultiIndex.from_tuples([('Maths', 'Mental Maths'),('Maths', 'Discrete Mathematics'),
('Maths', 'Applied Mathematics')])
# creating a DataFrame
dataFrame = pd.DataFrame([[67, 86, 78], [56, 92, 97], [92, 95, 91]],index=['John', 'Tom', 'Henry'],columns=items)
# DataFrame
print"DataFrame...\n",dataFrame
# stack multi-level columns
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
以上是 Python - 在 Pandas DataFrame 中堆叠多级列 的全部内容, 来源链接: utcz.com/z/338707.html