学习Pandas,第 10 课
英文原文: 10 - Lesson
- 从 DataFrame 到 Excel
- 从 Excel 到 DataFrame
- 从 DataFrame 到 JSON
- 从 JSON 到 DataFrame
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
从 DataFrame 到 Excel
# 创建一个 DataFrame
d = [1,2,3,4,5,6,7,8,9]
df = pd.DataFrame(d, columns = ['Number'])
df
Number | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
5 | 6 |
6 | 7 |
7 | 8 |
8 | 9 |
# 导出到 Excel
df.to_excel('./Lesson10.xlsx', sheet_name = 'testing', index = False)
print('Done')
Done
从 Excel 到 DataFrame
# Excel 文件的路径
# 按照你的要求修改文件路径
location = r'./Lesson10.xlsx'
# 读入 Excel 文件
df = pd.read_excel(location, 0)
df.head()
Number | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
df.dtypes
Number int64
dtype: object
df.tail()
Number | |
---|---|
4 | 5 |
5 | 6 |
6 | 7 |
7 | 8 |
8 | 9 |
从 DataFrame 到 JSON
df.to_json('Lesson10.json')
print('Done')
Done
从 JSON 到 DataFrame
# 按照你的要求修改文件路径
jsonloc = r'./Lesson10.json'
# read json file
df2 = pd.read_json(jsonloc)
df2
Number | |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 5 |
5 | 6 |
6 | 7 |
7 | 8 |
8 | 9 |
df2.dtypes
Number int64
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.