练习8-创建数据框
探索Pokemon数据
步骤1 导入必要的库
运行以下代码
import pandas as pd
步骤2 创建一个数据字典
运行以下代码
raw_data = {“name”: [‘Bulbasaur’, ‘Charmander’,‘Squirtle’,‘Caterpie’],
“evolution”: [‘Ivysaur’,‘Charmeleon’,‘Wartortle’,‘Metapod’],
“type”: [‘grass’, ‘fire’, ‘water’, ‘bug’],
“hp”: [45, 39, 44, 45],
“pokedex”: [‘yes’, ‘no’,‘yes’,‘no’]
}
步骤3 将数据字典存为一个名叫pokemon的数据框中
运行以下代码
pokemon = pd.DataFrame(raw_data)
pokemon.head()
evolution hp name pokedex type
0 Ivysaur 45 Bulbasaur yes grass
1 Charmeleon 39 Charmander no fire
2 Wartortle 44 Squirtle yes water
3 Metapod 45 Caterpie no bug
步骤4 数据框的列排序是字母顺序,请重新修改为name, type, hp, evolution, pokedex这个顺序
运行以下代码
pokemon = pokemon[[‘name’, ‘type’, ‘hp’, ‘evolution’,‘pokedex’]]
pokemon
name type hp evolution pokedex
0 Bulbasaur grass 45 Ivysaur yes
1 Charmander fire 39 Charmeleon no
2 Squirtle water 44 Wartortle yes
3 Caterpie bug 45 Metapod no
步骤5 添加一个列place
运行以下代码
pokemon[‘place’] = [‘park’,‘street’,‘lake’,‘forest’]
pokemon
name type hp evolution pokedex place
0 Bulbasaur grass 45 Ivysaur yes park
1 Charmander fire 39 Charmeleon no street
2 Squirtle water 44 Wartortle yes lake
3 Caterpie bug 45 Metapod no forest
步骤6 查看每个列的数据类型
运行以下代码
pokemon.dtypes
name object
type object
hp int64
evolution object
pokedex object
place object
dtype: object