(Datacamp)从零开始学python(4)——Dictionary&Pandas

Dictionary

# 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])

1)取代index函数,创造新的类型dictionary europe={”a“:b,…,…,}

# Definition of dictionary
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo' }

2)利用keys搜索

# Print out the keys in europe  输出关键字
print(europe.keys())

#确认某关键字确实存在
print('italy' in europe)          #输出结果是true or false

# Print out value that belongs to key 'norway'  输出keys对应的value
print(europe['norway'])

注意最后输出来的dictionaries are inherently unordered.就是顺序和你输进去的顺序不一致

  1. dictionary的关键字应该是不可变的,比如bool ,float,int等等,list由于是可变的所以不可以充当keys
  2. 由于字典用于索引,每个keys只能对应一个value,定义的时候就算后面写了第二个value,也是作废的
  3. 那要怎么增删或者变动dictionary呐?↓

3)增加新的数据,查询新的数据都很便洁

 #没有这个key的话就是增加新数据,有的话就是改变values
europe['italy'] = 'rome'

# Print out the keys in europe
 europe.keys(europe)
 .
 #delete
 del(europe['italy'])

Pandas part 1

instead of Numpy arrays,pandas can handle datas of diferent types
by creating dataframe

x={keys(column lables):[values(data,column by column)]}
import pandas as pd
pd.DataFrame(x)

#外部导入文件来输入数据,eg:

x = pd.read_csv('文件',index_col=0)# index_col=0,否则会是的第一列是数字012345而不是关键字

#或者也可以单独设置

cars.index=row_labels #自己设置row_lables就行

Pandas Part 2

Index and Select Data

  • Square brackets
  • Advanced methods
    • loc
    • iloc

1)square brackets

type(X[["country",....]])  #注意是两个方括号,一个的话 它会告诉你这个列的类型是Series 2333

2)Row Access[]——loc & iloc

loc :基于行列标签,iloc:基于数据的位置

brics.loc['RU',..,]  #row as Pandas Series
bris.loc[["RU",...,....]] # DataFram
eg:
bris.loc[["RU",...,....],["a","b"]]
#          行               列 输出为datafram形式, 前面的是行标签,后面的是列标签
#可以省略列,但要写行 ,若只想要列 可以[:,['a','b'.....,]]

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值