学习Pandas,第 5 课

英文原文: 05 - Lesson

我们将快速地看一下 stackunstack 这两个函数。

  1. # 导入库
  2. import pandas as pd
  3. import sys
  1. print('Python version ' + sys.version)
  2. print('Pandas version: ' + pd.__version__)
  1. Python version 3.6.1 | packaged by conda-forge | (default, Mar 23 2017, 21:57:00)
  2. [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)]
  3. Pandas version: 0.19.2
  1. # 我们的小数聚集
  2. d = {'one':[1,1],'two':[2,2]}
  3. i = ['a','b']
  4. # 创建一个 dataframe
  5. df = pd.DataFrame(data = d, index = i)
  6. df





















one two
a 1 2
b 1 2

  1. df.index
  1. Index(['a', 'b'], dtype='object')
  1. # 把列(column)放置到索引位置
  2. stack = df.stack()
  3. stack
  1. a one 1
  2. two 2
  3. b one 1
  4. two 2
  5. dtype: int64
  1. # 现在索引包含了原来的列名字
  2. stack.index
  1. MultiIndex(levels=[['a', 'b'], ['one', 'two']],
  2. labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
  1. unstack = df.unstack()
  2. unstack
  1. one a 1
  2. b 1
  3. two a 2
  4. b 2
  5. dtype: int64
  1. unstack.index
  1. MultiIndex(levels=[['one', 'two'], ['a', 'b']],
  2. labels=[[0, 0, 1, 1], [0, 1, 0, 1]])

T (转置),我们可以把列和索引交换位置。

  1. transpose = df.T
  2. transpose





















a b
one 1 1
two 2 2

  1. transpose.index
  1. 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.