学习Pandas,第 5 课
英文原文: 05 - Lesson
我们将快速地看一下 stack 和 unstack 这两个函数。
# 导入库
import pandas as pd
import sys
print('Python version ' + sys.version)
print('Pandas version: ' + pd.__version__)
Python version 3.6.1 | packaged by conda-forge | (default, Mar 23 2017, 21:57:00)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]
Pandas version: 0.19.2
# 我们的小数聚集
d = {'one':[1,1],'two':[2,2]}
i = ['a','b']
# 创建一个 dataframe
df = pd.DataFrame(data = d, index = i)
df
one | two | |
---|---|---|
a | 1 | 2 |
b | 1 | 2 |
df.index
Index(['a', 'b'], dtype='object')
# 把列(column)放置到索引位置
stack = df.stack()
stack
a one 1
two 2
b one 1
two 2
dtype: int64
# 现在索引包含了原来的列名字
stack.index
MultiIndex(levels=[['a', 'b'], ['one', 'two']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
unstack = df.unstack()
unstack
one a 1
b 1
two a 2
b 2
dtype: int64
unstack.index
MultiIndex(levels=[['one', 'two'], ['a', 'b']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
用 T (转置),我们可以把列和索引交换位置。
transpose = df.T
transpose
a | b | |
---|---|---|
one | 1 | 1 |
two | 2 | 2 |
transpose.index
Index(['one', 'two'], dtype='object')
This tutorial was created by HEDARO
本教程由派兰数据翻译
These tutorials are also available through an email course, please visit http://www.hedaro.com/pandas-tutorial to sign up today.