学习Pandas,第 6 课

英文原文: 06 - Lesson

我们看一下 groupby 这个函数。

  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,1,1,1],
  3. 'two':[2,2,2,2,2],
  4. 'letter':['a','a','b','b','c']}
  5. # 创建一个 dataframe
  6. df = pd.DataFrame(d)
  7. df










































letter one two
0 a 1 2
1 a 1 2
2 b 1 2
3 b 1 2
4 c 1 2

  1. # 创建一个 groupby 对象
  2. one = df.groupby('letter')
  3. # 在分组上应用 sum() 函数
  4. one.sum()































one two
letter
a 2 4
b 2 4
c 1 2

  1. letterone = df.groupby(['letter','one']).sum()
  2. letterone































two
letter one
a 1 4
b 1 4
c 1 2

  1. letterone.index
  1. MultiIndex(levels=[['a', 'b', 'c'], [1]],
  2. labels=[[0, 1, 2], [0, 0, 0]],
  3. names=['letter', 'one'])

你可能不想把用来分组的列名字作为索引,像下面的做法很容易实现。

  1. letterone = df.groupby(['letter','one'], as_index=False).sum()
  2. letterone






























letter one two
0 a 1 4
1 b 1 4
2 c 1 2

  1. letterone.index
  1. Int64Index([0, 1, 2], dtype='int64')

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.