pandas基础(2)_多重索引
1:多重索引的构造
>>> #下面显示构造pd.MultiIndex
>>> df1=DataFrame(np.random.randint(0,150,size=(6,3)),columns=['java','html5','python'])
>>> import pandas as pd
>>> df1=DataFrame(np.random.randint(0,150,size=(6,3)),columns=['java','html5','python'],index=pd.MultiIndex.from_arrays([['张三','张三','侯少','侯少','a','a'],['M','E','M','E','M','E']]))
>>> df1#因为Python自身的原因,对汉字的识别不是太好,所以汉字被?代替了
java html5 python
???? M 2 13 76
E 141 67 84
M 116 83 8
E 70 118 125
a M 74 0 76
E 111 31 8
>>> #使用元组tuple创建
df2=DataFrame(np.random.randint(0,150,size=(6,3)),columns=['java','html','python'],index=pd.MultiIndex.from_tuples([('a','1'),('a','11'),('b','1'),('b','11'),('c','1'),('c','11')]))
>>> df2
java html python
a 1 32 144 99
11 104 101 16
b 1 93 98 41
11 59 30 45
c 1 91 17 149
11 9 28 59
>>> #使用product
df2=DataFrame(np.random.randint(0,150,size=(6,3)),columns=['java','html','python'],index=pd.MultiIndex.from_product([['zhangsan ','lisi','wangwu'],['mid','end']]))
>>> df2
java html python
zhangsan mid 50 128 54
end 3 4 91
lisi mid 4 93 110
end 116 123 122
wangwu mid 88 25 54
end 48 146 57
>>> #对dataFrame同样可以设置成多重索引
df2=DataFrame(np.random.randint(0,150,size=(3,6)),columns=pd.MultiIndex.from_product([['java','html','python'],['mid','end']]),index=['张三','李四','王五'])
>>> df2
java html python
mid end mid end mid end
???? 33 38 112 70 113 110
???? 29 46 132 91 117 128
???? 73 56 118 82 132 39
>>>
>>> df2['java','mid']#查询某一列
???? 33
???? 29
???? 73
Name: (java, mid), dtype: int32
>>> s['zhangsan':'lisi']#其实就是一个Series
Series([], dtype: int64)
>>> s.iloc[0:3]
a 0 1
1 2
b 0 3
dtype: int64
>>> #切片
>>> df2['张三':'王五']
java html python
mid end mid end mid end
???? 33 38 112 70 113 110
???? 29 46 132 91 117 128
???? 73 56 118 82 132 39
>>>df2.iloc[0:4]#推荐使用
Df2[‘张三’,‘期中’]和df2.loc[‘张三’].loc[‘期中’]
#如何一级索引有多个,对二级索引会遇到问题,也就是说,无法直接对二级进行索引
必须把二级索引变成一级索引才可以进行索引
>>> df2.stack()
html java python
???? end 70 38 110
mid 112 33 113
end 91 46 128
mid 132 29 117
end 82 56 39
mid 118 73 132
>>> #stack =堆----》行
end mid
???? html 70 112
java 38 33
python 110 113
html 91 132
java 46 29
python 128 117
html 82 118
java 56 73
python 39 132
>>> #默认为-1
2:多重索引的计算
>>> df2
java html python
mid end mid end mid end
???? 33 38 112 70 113 110
???? 29 46 132 91 117 128
???? 73 56 118 82 132 39
>>> df1.sum()
java 514
html5 312
python 377
dtype: int64
>>> df1.sum(axis=0)
java 514
html5 312
python 377
dtype: int64
>>> df1.sum(axis=1)#对列
???? M 91
E 292
M 207
E 313
a M 150
E 150
dtype: int64
>>> df1.sum(axis=1)#对列求和,得到每行的和
???? M 91
E 292
M 207
E 313
a M 150
E 150
dtype: int64
>>> df1.std
<bound method DataFrame.std of java html5 python
???? M 2 13 76
E 141 67 84
M 116 83 8
E 70 118 125
a M 74 0 76
E 111 31 8>
>>> #求方差
>>> df1.std(axis=1)
???? M 39.929104
E 38.759945
M 55.344376
E 29.938827
a M 43.312816
E 54.064776
dtype: float64
>>> df1.max()
java 141
html5 118
python 125
dtype: int32
3多重索引的拼接
>>> nd = np.random.randint(0,10,size=(3,3))
>>> nd
array([[9, 9, 4],
[7, 2, 4],
[1, 6, 1]])
>>> np.concatenate ((nd,nd),axis=0)#在列方向就行拼接
array([[9, 9, 4],
[7, 2, 4],
[1, 6, 1],
[9, 9, 4],
[7, 2, 4],
[1, 6, 1]])
>>> np.concatenate ([nd,nd],axis=1)#在行方向进行拼接
array([[9, 9, 4, 9, 9, 4],
[7, 2, 4, 7, 2, 4],
[1, 6, 1, 1, 6, 1]])
>>> def make_df(cols,inds):
data = {c:[c+str(i) for i in cols]for c in cols}
return DataFrame(data,index=inds,columns=cols)
>>> make_df(['A','B'],[1,2])
A B
1 AA BA
2 AB BB
>>> df1=make_df(list('AB'),[0,1])
>>> df2=make_df(list('AB'),[2,3])
>>> pd.concat ([df1,df2])#默认在列方向进行拼接
A B
0 AA BA
1 AB BB
2 AA BA
3 AB BB
>>> #优先增加行数
>>> pd.concat ((df1,df2),axis=1)
A B A B
0 AA BA NaN NaN
1 AB BB NaN NaN
2 NaN NaN AA BA
3 NaN NaN AB BB
>>> #注意index在级联时可以重复
3)
>>> #列名可以相同但是不建议
>>> df3= make_df(list('AB'),[0,1])
>>> df4=make_df(list('VB'),[1,2])
>>> pd.concat((df3,df4))#只能传入一个参数
A B V
0 AA BA NaN
1 AB BB NaN
1 NaN BV VV
2 NaN BB VB
>>> #3种连接方式
>>> #1:外连接:补NaN(默认模式)
>>> df1= make_df(list('AB'),[1,3])
>>> df2= make_df(list('AB'),[2,4])
>>> df2= make_df(list('BC'),[2,4])
>>> pd.concat ([df1,df2],join='inner')#连接都有的部分
B
1 BA
3 BB
2 BB
4 BC
>>> pd.concat ([df1,df2],join='outer')
A B C
1 AA BA NaN
3 AB BB NaN
2 NaN BB CB
4 NaN BC CC
>>> #内连接只连接匹配项
>>> #3:连接指定轴 join_axes所以CDF的F便不显示了
>>> df3= make_df(list('ACD'),[0,1,2])
>>> df4= make_df(list('CDF'),[3,4,5])
>>> pd.concat([df3,df4],join_axes=[df3.columns])
A C D
0 AA CA DA
1 AC CC DC
2 AD CD DD
3 NaN CC DC
4 NaN CD DD
5 NaN CF DF
>>> #join_axes 某一个DataFrame列索引为新的列索引值
>>> #3使用append()函数添加
>>> #concat方法属于pandas
>>> #append()在后面添加
>>> #concat([df1,df2])
>>> #df1.append(df2)
>>> #merge与concat的区别是,merge需要依据某一共同的行或列来进行合并
>>> #使用pd.merge()合并时,会自动根据两者相同column名称的那一属性,作为key来进行合并,注意每一列的顺序不要求一致
>>> #一对一合并
>>> df1 = DataFrame({'employee':['po','sara','danis'],'group':['sail','counting','marcketing']})
>>> df2 = DataFrame({'employee':['po','sara','danis'],'work_time':[2,3,1]})
>>> df1
employee group
0 po sail
1 sara counting
2 danis marcketing
>>> df2
employee work_time
0 po 2
1 sara 3
2 danis 1
>>> pd.merge (df1,df2)
employee group work_time
0 po sail 2
1 sara counting 3
2 danis marcketing 1
>>> pd.concat([df1,df2])
employee group work_time
0 po sail NaN
1 sara counting NaN
2 danis marcketing NaN
0 po NaN 2.0
1 sara NaN 3.0
2 danis NaN 1.0
>>> df3 = DataFrame({'employee':['po','sara','liulei'],'work_time':[2,3,1]})
>>> pd.merge(df1,df3)
employee group work_time
0 po sail 2
1 sara counting 3
>>> #merge只合并相同属性里面都有的项
>>> #下面是merge的多对一的合并
>>> df1 = DataFrame({'employee':['po','sara','danis'],'work_time':[2,3,1]})
>>> df2 = DataFrame({'employee':['po','po','danis'],'group':['sail','counting','marcketing']})
>>> pd.merge(df1,df2)
employee work_time group
0 po 2 sail
1 po 2 counting
2 danis 1 marcketing
>>> #出现了两个po
>>> #下面是多对多的合并
>>> df1 = DataFrame({'employee':['po','sara','danis'],'group':['sail','counting','marcketing']})
>>> df1 = DataFrame({'employee':['po','po','danis'],'group':['sail','counting','marcketing']})
>>> df2 = DataFrame({'employee':['po','po','danis'],'work_time':[2,3,1]})
>>> pd.merge(df1,df2)
employee group work_time
0 po sail 2
1 po sail 3
2 po counting 2
3 po counting 3
4 danis marcketing 1
>>> #1*2*2的模式
>>> #使用merge多对多可以来处理重名等数据的情况
>>> df3= DataFrame({'employee':['po','Summer','Flower'],'group':['sail','marking','serch'],'WorkTime':[1,2,3]})
>>> df4= DataFrame({'employee':['po','Summer','Flower'],'group':['sail','marking','serch'],'salary':[12000,20000,10002]})
>>> df3
WorkTime employee group
0 1 po sail
1 2 Summer marking
2 3 Flower serch
>>> df4
employee group salary
0 po sail 12000
1 Summer marking 20000
2 Flower serch 10002
>>> pd.merge(df3,df4)
WorkTime employee group salary
0 1 po sail 12000
1 2 Summer marking 20000
2 3 Flower serch 10002
>>> df3= DataFrame({'employee':['po','Winter','Flower'],'group':['marketing','marking','serch'],'WorkTime':[1,2,3]})
>>> pd.merge(df3,df4)
WorkTime employee group salary
0 3 Flower serch 10002
>>> pd.merge(df3,df4,on='employee')
WorkTime employee group_x group_y salary
0 1 po marketing sail 12000
1 3 Flower serch serch 10002
>>> #出现两行数据的原因是指定了employee相同就可以合并
>> pd.merge(df3,df4,on='group')
WorkTime employee_x group employee_y salary
0 2 Winter marking Summer 20000
1 3 Flower serch Flower 10002
>>> pd.merge(df3,df4,on='group',suffixes=['_A','_B'])
WorkTime employee_A group employee_B salary
0 2 Winter marking Summer 20000
1 3 Flower serch Flower 10002
>>> df3= DataFrame({'employee':['po','Winter','Flower'],'group':['marketing','marking','serch'],'WorkTime':[1,2,3]})
>>> df4= DataFrame({'employer':['po','Summer','Flower'],'group':['sail','marking','serch'],'salary':[12000,20000,10002]})
>>> pd.merge(df3,df4)
WorkTime employee group employer salary
0 2 Winter marking Summer 20000
1 3 Flower serch Flower 10002
>>> pd.merge(df3,df4,left_on='employee',right_on='employer')
WorkTime employee group_x employer group_y salary
0 1 po marketing po sail 12000
1 3 Flower serch Flower serch 10002
>>> #df3主键key为employee和df4主键为employer,两者不同但又想相互匹配时,可以指定前者的left_on为employee和后者的right_on为employer这时两者可以进行匹配
>>> #内合并与外合并
>>> #内合并只保留两者都有的数据
>>> df1=DataFrame({'age':[18,22,33],'height':[175,169,180]})
>>> df1=DataFrame({'age':[18,23,32],'height':[175,169,180]})
>>> df2=DataFrame({'age':[18,22,33],'weight':[175,169,180]})
>>> pd.merge(df1,df2)
age height weight
0 18 175 175
>>> pd.merge(df1,df2,how='outer')
age height weight
0 18 175.0 175.0
1 23 169.0 NaN
2 32 180.0 NaN
3 22 NaN 169.0
4 33 NaN 180.0
>>> #默认为内合并,通过how可以指定合并类型
>>>
>>> pd.merge(df1,df2,how='left')
age height weight
0 18 175 175.0
1 23 169 NaN
2 32 180 NaN
>>> pd.merge(df1,df2,how='right')
age height weight
0 18 175.0 175
1 22 NaN 169
2 33 NaN 180
>>> #left保留前者的数据,right保留后者数据
>>> #left保留前者df1的数据,right保留后者df2数据
>>> #下面是列冲突
>>> df3= DataFrame({'employee':['po','Winter','Flower'],'group':['marketing','marking','serch'],'WorkTime':[1,2,3]})
>>> df4= DataFrame({'employee':['po','Summer','Flower'],'group':['sail','marking','serch'],'salary':[12000,20000,10002]})
>>> pd.merge(df3,df4)
WorkTime employee group salary
0 3 Flower serch 10002
>>> pd.merge(df3,df4,on='employee',suffixes=['_李','_王'])
WorkTime employee group_?? group_?? salary
0 1 po marketing sail 12000
1 3 Flower serch serch 10002
>>> #因为两者的employee和group相同,当指定employee为主键时,suffixes修改的就是group
4:总结:
多重索引也是pandas里非常重要的知识点,要牢牢掌握
pandas基础(2)_多重索引的更多相关文章
- pandas基础(3)_数据处理
1:删除重复数据 使用duplicate()函数检测重复的行,返回元素为bool类型的Series对象,每个元素对应一行,如果该行不是第一次出现,则元素为true >>> df =D ...
- 数据可视化基础专题(六):Pandas基础(五) 索引和数据选择器(查找)
1.序言 如何切片,切块,以及通常获取和设置pandas对象的子集 2.索引的不同选择 对象选择已经有许多用户请求的添加,以支持更明确的基于位置的索引.Pandas现在支持三种类型的多轴索引. .lo ...
- 利用Python进行数据分析(11) pandas基础: 层次化索引
层次化索引 层次化索引指你能在一个数组上拥有多个索引,例如: 有点像Excel里的合并单元格对么? 根据索引选择数据子集 以外层索引的方式选择数据子集: 以内层索引的方式选择数据: 多重索引S ...
- 基于 Python 和 Pandas 的数据分析(2) --- Pandas 基础
在这个用 Python 和 Pandas 实现数据分析的教程中, 我们将明确一些 Pandas 基础知识. 加载到 Pandas Dataframe 的数据形式可以很多, 但是通常需要能形成行和列的数 ...
- Python数据分析入门之pandas基础总结
Pandas--"大熊猫"基础 Series Series: pandas的长枪(数据表中的一列或一行,观测向量,一维数组...) Series1 = pd.Series(np.r ...
- pandas基础学习
1.导入两个数据分析重要的模块import numpy as npimport pandas as pd2.创建一个时间索引,所谓的索引(index)就是每一行数据的id,可以标识每一行的唯一值dat ...
- 利用Python进行数据分析(12) pandas基础: 数据合并
pandas 提供了三种主要方法可以对数据进行合并: pandas.merge()方法:数据库风格的合并: pandas.concat()方法:轴向连接,即沿着一条轴将多个对象堆叠到一起: 实例方法c ...
- 利用Python进行数据分析(9) pandas基础: 汇总统计和计算
pandas 对象拥有一些常用的数学和统计方法. 例如,sum() 方法,进行列小计: sum() 方法传入 axis=1 指定为横向汇总,即行小计: idxmax() 获取最大值对应的索 ...
- 利用Python进行数据分析(8) pandas基础: Series和DataFrame的基本操作
一.reindex() 方法:重新索引 针对 Series 重新索引指的是根据index参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...
随机推荐
- JavaEE详解
本文主要讲JavaEE相关知识. 一 JavaEE 简介 JavaEE是很多技术的合集.提供了一套做B/S结构应用时,可能遇到问题的一套解决方案. 例如:处理客服端请求的servlet技术方案.处理数 ...
- BCH硬分叉,BitcoinABC强势逆袭BitcoinSV
最近币圈讨论最多的就是BCH的硬分叉,今天凌晨BCH硬分叉在众多币圈大佬关注下落下帷幕,此次分叉大站BitcoinABC强势完胜BitcoinSV.吴忌寒在推特上表示:祝贺!在这个新的区块之后 ...
- ME11创建信息记录 Function
转自 http://blog.csdn.net/zeewjj/article/details/7941530 CALL FUNCTION 'ME_DIRECT_INPUT_INFORECORD' D ...
- [数据挖掘课程笔记]无监督学习——聚类(clustering)
什么是聚类(clustering) 个人理解:聚类就是将大量无标签的记录,根据它们的特点把它们分成簇,最后结果应当是相同簇之间相似性要尽可能大,不同簇之间相似性要尽可能小. 聚类方法的分类如下图所示: ...
- Java for LeetCode 102 Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
- ios点击链接直接跳转到 App Store 指定应用下载页面
//跳转到应用页面 NSString *str = [NSString stringWithFormat:@"http://itunes.apple.com/us/app/id%d&quo ...
- react-native修改android包名
安卓已包名作为应用的唯一id,相对iOS来说改起来就不是那么方便,但为了能正式发布自己的应用,还是得改过来. 假设包名为com.exease.etd.objective,以下地方需要修改. 首先是两个 ...
- JMS消息可靠机制
ActiveMQ消息签收机制: 客戶端成功接收一条消息的标志是一条消息被签收,成功应答. 消息的签收情形分两种: 1.带事务的session 如果session带有事务,并且事务成功提交,则消息被自动 ...
- 大数据 - Zookeeper
Zookeeper 1. Zookeeper概念简介: Zookeeper是一个分布式协调服务:就是为用户的分布式应用程序提供协调服务 A.zookeeper是为别的分布式程序服务的 B.Zooke ...
- java 创建 HMAC 签名
ava 创建 HMAC 签名 psd素材 1. []ComputopTest.java package com.javaonly.hmac.test; import java.io.IOExcepti ...