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.就是顺序和你输进去的顺序不一致
- dictionary的关键字应该是不可变的,比如bool ,float,int等等,list由于是可变的所以不可以充当keys
- 由于字典用于索引,每个keys只能对应一个value,定义的时候就算后面写了第二个value,也是作废的
- 那要怎么增删或者变动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'.....,]]