学习Pandas,第 10 课

英文原文: 10 - Lesson

  • 从 DataFrame 到 Excel
  • 从 Excel 到 DataFrame
  • 从 DataFrame 到 JSON
  • 从 JSON 到 DataFrame
  1. import pandas as pd
  2. 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

从 DataFrame 到 Excel

  1. # 创建一个 DataFrame
  2. d = [1,2,3,4,5,6,7,8,9]
  3. df = pd.DataFrame(d, columns = ['Number'])
  4. df














































Number
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

  1. # 导出到 Excel
  2. df.to_excel('./Lesson10.xlsx', sheet_name = 'testing', index = False)
  3. print('Done')
  1. Done

从 Excel 到 DataFrame

  1. # Excel 文件的路径
  2. # 按照你的要求修改文件路径
  3. location = r'./Lesson10.xlsx'
  4. # 读入 Excel 文件
  5. df = pd.read_excel(location, 0)
  6. df.head()






























Number
0 1
1 2
2 3
3 4
4 5

  1. df.dtypes
  1. Number int64
  2. dtype: object
  1. df.tail()






























Number
4 5
5 6
6 7
7 8
8 9

从 DataFrame 到 JSON

  1. df.to_json('Lesson10.json')
  2. print('Done')
  1. Done

从 JSON 到 DataFrame

  1. # 按照你的要求修改文件路径
  2. jsonloc = r'./Lesson10.json'
  3. # read json file
  4. df2 = pd.read_json(jsonloc)
  1. df2














































Number
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

  1. df2.dtypes
  1. Number int64
  2. 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.