知识点转自:
http://python.jobbole.com/89081/?utm_source=blog.jobbole.com&utm_medium=relatedPosts
>>> series1=pd.Series([1,2,3],index=['A','B','C'])
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
series1=pd.Series([1,2,3],index=['A','B','C'])
NameError: name 'pd' is not defined
>>> import pandas as pd
>>> import numpy as np
>>> series =pd.Series ([1,2,3],index=['A','B','C'])
>>> print('series['A'] = {}\n'.format(series))
SyntaxError: invalid syntax
>>> print('series['A'] = {}\n'.format(series['A']))
SyntaxError: invalid syntax
>>> print('series.A = {} \n'.format(series.A))
series.A = 1
>>> print('series['A'] = {} \n'.format(series['A']))
SyntaxError: invalid syntax
>>> print('series['B'] = {}\n'.format(series['B']))
SyntaxError: cannot mix bytes and nonbytes literals
>>> print("series['B'] = {}\n".format(series['B']))
series['B'] = 2
>>> print("series['A'] = {}\n".format(series['A']))
series['A'] = 1
>>> #双引号、单引号注意;[] . --------访问数据
>>> #注:这里的数据访问方法既适用于Series,也适用于DataFrame。
>>> #----------------------------loc与iloc-----------------------------
>>> #loc:通过行和列的索引来访问数据
>>> #iloc:通过行和列的下标来访问数据
>>> df1 = pd.DataFrame({"note" : ["C", "D", "E", "F", "G", "A", "B"],
"weekday": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]},
index=['1', '2', '3', '4', '5', '6', '7'])
>>> print(format(df1))
note weekday
1 C Mon
2 D Tue
3 E Wed
4 F Thu
5 G Fri
6 A Sat
7 B Sun
>>> print("df1.loc['2']:\n{}\n.format(df1.loc['2']))
SyntaxError: EOL while scanning string literal
>>> print("df1.loc['2']:\n{}\n".format(df1.loc['2']))
df1.loc['2']:
note D
weekday Tue
Name: 2, dtype: object
>>> #这里通过索引'2'可以方法到第2行的所有数据
>>> print("series.loc['B':'C']=\n{}\n".format(series.loc['B':'C']))
series.loc['B':'C']=
B 2
C 3
dtype: int64
>>> print("df1.iloc[2:4]=\n{}\n."format(df1.iloc[2:4]))
SyntaxError: invalid syntax
>>> print("df1.iloc[2:4]=\n{}\n".format(df1.iloc[2:4]))
df1.iloc[2:4]=
note weekday
3 E Wed
4 F Thu
>>> print("df1.iloc[3:4]=\n{}\n".format(df1.iloc[2:4]))
df1.iloc[3:4]=
note weekday
3 E Wed
4 F Thu
>>> #------------------------at与iat-----------------------
>>> #这两个操作符用来访问单个的元素值(Scalar Value)。类似的:at:通过行和列的[【索引】来访问数据;iat:通过行和列的【下标】来访问数据。
>>> print("series.at['C']={}\n".format(series.at['C']))
series.at['C']=3
>>> print("df1.iloc[2:4]=\n{}\n".format(df1.iloc[4:1]))
df1.iloc[2:4]=
Empty DataFrame
Columns: [note, weekday]
Index: []
>>> print("df1.iat[4:1]=\n{}\n".format(df1.iat[4:1]))
>>> print("df1.iloc[2:4]=\n{}\n".format(df1.iloc[4,1]))
df1.iloc[2:4]=
Fri
>>> print("df1.iloc[2:4]={}\n".format(df1.iloc[4,1]))
df1.iloc[2:4]=Fri
>>> print("df1.iloc[5:weekday]={}\n".format(df1.iloc[4,1]))
df1.iloc[5:weekday]=Fri
>>> print("df1.iloc[5:weekday]={}\n".format(df1.iat[4,1]))
df1.iloc[5:weekday]=Fri
>>> print("df1.iat[5:weekday]={}\n".format(df1.iat[4,1]))
df1.iat[5:weekday]=Fri
>>> #------------------------Index对象-------------------------------
>>> #在入门教程我们也已经简单介绍过Index,Index提供了查找,数据对齐和重新索引所需的基础数据结构。 最直接的,我们可以通过一个数组来创建Index对象。在创建的同时我们还可以通过name指定索引的名称:
>>> index = pd.Index('C','D','E','F','G','A','B'], name='note')
SyntaxError: invalid syntax
>>> index = pd.Index(['C','D','E','F','G','A','B'], name='note')
>>> print(index)
Index(['C', 'D', 'E', 'F', 'G', 'A', 'B'], dtype='object', name='note')
>>> #Index类提供了很多的方法进行各种操作,这个建议读者直接查询API说明即可,这里不多做说明。稍微提一下的是,Index对象可以互相之间做集合操作,例如:
>>> a = pd.Index([1,2,3,4,5])
>>> b = pd.Index([3,4,5,6,7])
>>> print("a|b = {}\n".format(a|b))
a|b = Int64Index([1, 2, 3, 4, 5, 6, 7], dtype='int64')
>>> print("a&b = {}\n".format(a&b))
a&b = Int64Index([3, 4, 5], dtype='int64')
>>> print("a.difference(b) = {}\n".format(a.difference(b)))
a.difference(b) = Int64Index([1, 2], dtype='int64')
>>> print("b.difference(a) = {}\n".format(b.difference(a)))
b.difference(a) = Int64Index([6, 7], dtype='int64')
>>> #创建测试数据
>>> df = pd.DataFrame({'class':['A','A','A','B','B','B','C','C'],
'id':['a','b','c','a','b','c','a','b'],
'value':[1,2,3,4,5,6,7,8]})
>>> print(format(df))
class id value
0 A a 1
1 A b 2
2 A c 3
3 B a 4
4 B b 5
5 B c 6
6 C a 7
7 C b 8
>>> df = df.set_index(['class','id'])#通过set_index设为多重索引
>>> print(format(df))
value
class id
A a 1
b 2
c 3
B a 4
b 5
c 6
C a 7
b 8
>>> df.loc[('A',slice(None)),:]
value
class id
A a 1
b 2
c 3
>>> df.loc[(slice(None),'a'),:]
value
class id
A a 1
B a 4
C a 7
>>> #前面的例子对应的index列为数字或字母,是【有序的】
>>> #创建无序测试数据
>>> df2 = pd.DataFrame({'课程':['语文','语文','数学','数学'],'得分':['最高','最低','最高','最低'],'分值':[90,50,100,60]})
>>> print(format(df2))
课程 得分 分值
0 语文 最高 90
1 语文 最低 50
2 数学 最高 100
3 数学 最低 60
>>> df2 = df2.set_index(['课程','得分'])
>>> print(df2)
分值
课程 得分
语文 最高 90
最低 50
数学 最高 100
最低 60
>>> print(format(df2))
分值
课程 得分
语文 最高 90
最低 50
数学 最高 100
最低 60
>>> df2.loc[('语文',slice(None)),:]
分值
课程 得分
语文 最高 90
最低 50
>>> df2.loc[(slice(None),'最高'),:]
分值
课程 得分
语文 最高 90
数学 最高 100
>>> multiIndex1 = pd.MultiIndex.from_arrays([
['Geagle', 'Geagle', 'Geagle', 'Geagle',
'Epple', 'Epple', 'Epple', 'Epple', 'Macrosoft',
'Macrosoft', 'Macrosoft', 'Macrosoft', ],
['S1', 'S2', 'S3', 'S4', 'S1', 'S2', 'S3', 'S4', 'S1', 'S2', 'S3', 'S4']],
names=('Company', 'Turnover'))
>>> print(format(multiIndex1))
MultiIndex(levels=[['Epple', 'Geagle', 'Macrosoft'], ['S1', 'S2', 'S3', 'S4']],
labels=[[1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2], [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]],
names=['Company', 'Turnover'])
>>> #从这个输出可以看出,MultiIndex中的levels数组数量对应了索引的级别数量,labels对应了levels中元素的下标
>>> #下面我们用一个随机数来构造一个DataFrame:
>>> df = pd.DataFrame(data=np.random.randint(0, 1000, 36).reshape(-1, 12),
index=[2016, 2017, 2018],
columns=multiIndex1)
>>> print("df = \n{}\n".format(df))
df =
Company Geagle Epple ... Macrosoft
Turnover S1 S2 S3 S4 S1 ... S4 S1 S2 S3 S4
2016 502 629 740 686 430 ... 636 510 64 330 95
2017 27 352 953 170 942 ... 630 411 576 263 964
2018 332 581 626 974 904 ... 187 498 910 599 165
[3 rows x 12 columns]
>>> #这里创建出了36个[0, 1000)之间的随机数,然后组装成3行12列的矩阵
>>> #这个输出很直观的可以看出三个公司在三年内每个季度的营业额。 有了多级索引,我们可以方便的进行数据的筛选,例如:
>>> df.loc[2017, (['Geagle', 'Epple', 'Macrosoft'] ,'S1')]#筛选出三个公司2017年第一季度的营业额
Company Turnover
Geagle S1 27
Epple S1 942
Macrosoft S1 411
Name: 2017, dtype: int32
>>> df.loc[2018, 'Geagle']#筛选出Geagle公司2018年每个季度的营业额
Turnover
S1 332
S2 581
S3 626
S4 974
Name: 2018, dtype: int32