栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

DataCamp: Intermediate Python-Dictionaries & Pandas

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DataCamp: Intermediate Python-Dictionaries & Pandas

觉得再学一次挺好的,可以复习很多知识,还有很多之前模模糊糊不太懂的地方可以弄清楚。加油

Table of Contents

Dictionaries

Motivations for dictionariesCreate DictionaryAccess DictionaryList vs. DictionaryDictionary Manipulation-addDiactionary Manipulation (2)- updateDictionariception Pandas

Dictionary to Dataframe(1)Dictionary to Dataframe(2)CSV to Dataframe(1)CSV to Dataframe(2)Square Brackets(1)Square Brackets(2)loc and iloc(1)loc and iloc(2)loc and iloc(3)


Dictionaries Motivations for dictionaries
# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']

# Get index of 'germany': ind_ger
ind_ger = countries.index('germany')

# Use ind_ger to print out capital of Germany
print(capitals[ind_ger])
Create Dictionary

keys have to be “immutable” objects. cannot be list, for example.

# Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']

# From string in countries and capitals, create dictionary europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }

# Print europe
print(europe)
Access Dictionary
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }

# Print out the keys in europe
print(europe.keys())

# Print out value that belongs to key 'norway'
print(europe['norway'])
List vs. Dictionary
ListDictionary
Select, update, and remove with [ ]select, updated and remove with [ ]
Indexed by range of numbersindexed by unique keys
Dictionary Manipulation-add
# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }

# Add italy to europe
europe['italy'] = 'rome'

# Print out italy in europe
print('italy' in europe)
# Add poland to europe
europe['poland'] = 'warsaw'

# Print europe
print(europe)
Diactionary Manipulation (2)- update

del(europe[‘australia’])

# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'bonn',
          'norway':'oslo', 'italy':'rome', 'poland':'warsaw',
          'australia':'vienna' }

# Update capital of germany
europe['germany'] = 'berlin'

# Remove australia

del(europe['australia'])
# Print europe
print(europe)
Dictionariception
# Dictionary of dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':46.77 },
           'france': { 'capital':'paris', 'population':66.03 },
           'germany': { 'capital':'berlin', 'population':80.62 },
           'norway': { 'capital':'oslo', 'population':5.084 } }


# Print out the capital of France

print(europe['france']['capital'])
# Create sub-dictionary data
data = {'capital':'rome', 'population': 59.83}

# Add data to europe under key 'italy'

europe['italy'] = data
# Print europe
print(europe)

Pandas Dictionary to Dataframe(1)
# Pre-defined lists
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr =  [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]

# import pandas as pd
import pandas as pd

# Create dictionary my_dict with three key:value pairs: my_dict
my_dict = {'country': names, 'drives_right' : dr, 'cars_per_cap': cpc}

# Build a Dataframe cars from my_dict: cars
cars = pd.Dataframe(my_dict)

# Print cars
print(cars)
Dictionary to Dataframe(2)

cars.index = row_labels

import pandas as pd

# Build cars Dataframe
names = ['United States', 'Australia', 'Japan', 'India', 'Russia', 'Morocco', 'Egypt']
dr =  [True, False, False, False, True, True, True]
cpc = [809, 731, 588, 18, 200, 70, 45]
cars_dict = { 'country':names, 'drives_right':dr, 'cars_per_cap':cpc }
cars = pd.Dataframe(cars_dict)
print(cars)

# Definition of row_labels
row_labels = ['US', 'AUS', 'JPN', 'IN', 'RU', 'MOR', 'EG']

# Specify row labels of cars
cars.index = row_labels

# Print cars again
print(cars)
CSV to Dataframe(1)
# import pandas as pd
import pandas as pd

# import the cars.csv data: cars
cars = pd.read_csv('cars.csv')

# Print out cars
print(cars)
CSV to Dataframe(2)

cars = pd.read_csv(‘cars.csv’, index_col = 0)

# import pandas as pd
import pandas as pd

# Fix import by including index_col
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out cars
print(cars)
Square Brackets(1)

In the sample code, the same cars data is imported from a CSV files as a Pandas Dataframe. To select only the cars_per_cap column from cars, you can use:cars[‘cars_per_cap’]
cars[[‘cars_per_cap’]]
⚠️The single bracket version gives a Pandas Series, the double bracket version gives a Pandas Dataframe.

# import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out country column as Pandas Series
print(cars['country'])

# Print out country column as Pandas Dataframe
print(cars[['country']])

# Print out Dataframe with country and drives_right columns
print(cars[['country','drives_right']])

print(cars[[‘country’,‘drives_right’]])

Square Brackets(2)
# import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out first 3 observations

print(cars[:3])
# Print out fourth, fifth and sixth observation
print(cars[3:6])

loc and iloc(1)

With loc and iloc you can do practically any data selection operation on Dataframes you can think of.
loc is label-based, which means that you have to specify rows and columns based on their row and column labels.
iloc is integer index based, so you have to specify rows and columns by their integer index like you did in the previous exercise.

e.g.

cars.loc['RU']
cars.iloc[4]

cars.loc[['RU']]
cars.iloc[[4]]

cars.loc[['RU', 'AUS']]
cars.iloc[[4, 1]]
# import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out observation for Japan

print(cars.loc['JPN'])
# Print out observations for Australia and Egypt
print(cars.loc[['AUS', 'EG']])
loc and iloc(2)
# import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out drives_right value of Morocco

print(cars.loc['MOR']['drives_right'])
# Print sub-Dataframe
print(cars.loc[['RU', 'MOR']][['country','drives_right']])
loc and iloc(3)

print(cars.loc[:,[‘drives_right’]])

print(cars.loc[:,[‘cars_per_cap’, ‘drives_right’]])

# import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)

# Print out drives_right column as Series
print(cars.loc[:,'drives_right'])

# Print out drives_right column as Dataframe

print(cars.loc[:,['drives_right']])
# Print out cars_per_cap and drives_right as Dataframe

print(cars.loc[:,['cars_per_cap', 'drives_right']])
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/754756.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号