Python数据分析_Pandas01_数据框的创建和选取
主要内容:
- 创建数据表
- 查看数据表
- 数据表索引、选取部分数据
- 通过标签选取
.loc - 多重索引选取
- 位置选取
.iloc - 布尔索引
- 通过标签选取
Object Creation 新建数据
- 用list建series序列
In [73]: s = pd.Series([1,3,5,np.nan,6,8])
In [74]: s
Out[74]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
- 用numpy array建dataframe
In [75]: dates = pd.date_range('20130101', periods=6)
In [76]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
In [77]: df
Out[77]:
A B C D
2013-01-01 -0.411674 0.273549 0.629843 1.881497
2013-01-02 1.240512 0.970725 0.033099 1.553420
2013-01-03 -0.544326 0.545738 -1.325810 0.130738
2013-01-04 1.044803 -0.117151 0.874583 2.278227
2013-01-05 -2.194728 -2.536257 0.478644 0.057728
2013-01-06 -1.092031 1.249952 1.598761 -0.153423
#---pd.date_range?---
In [115]: pd.date_range(start='12/31/2011', end='12/31/2013', freq='A')
Out[115]: DatetimeIndex(['2011-12-31', '2012-12-31', '2013-12-31'], dtype='datetime64[ns]', freq='A-DEC')
- 用dictionary
In [78]: df2 = pd.DataFrame({ 'A' : 1.,
...: 'B' : pd.Timestamp('20130102'),
...: 'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
...: 'D' : np.array([3] * 4,dtype='int32'),
...: 'E' : pd.Categorical(["test","train","test","train"]),
...: 'F' : 'foo' })
...: df2
...:
Out[78]:
A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
1 1.0 2013-01-02 1.0 3 train foo
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo
In [80]: df2.dtypes
Out[80]:
A float64
B datetime64[ns]
C float32
D int32
E category
F object
dtype: object
在ipython中可以使用<tab>键进行自动补充,它会列出数据对象可以执行的操作。
查看数据
df.head()
df.tail(3)
df.index
df.columns #返回一个这样的东西:pandas.indexes.numeric.Int64Index
df.values #提取出数据框的数值,返回一个array
数据选取
建议 使用pandas的数据选取方法:.at, .iat, .loc, .iloc, .ix. 这些更高效。
df['A'] # 选取某一列,返回一个Series,== df.A,【只能选某一列,不能用":"多选。】
df[0:3] # 选行
df['20130102':'20130104']
通过标签label选取,.loc
用.loc[]选取数据时,方括号里对应的是:[行,列](逗号分隔),如果只有一个值,默认是行。可以用“:”。
In [82]: df
Out[82]:
A B C D
2013-01-01 -0.411674 0.273549 0.629843 1.881497
2013-01-02 1.240512 0.970725 0.033099 1.553420
2013-01-03 -0.544326 0.545738 -1.325810 0.130738
2013-01-04 1.044803 -0.117151 0.874583 2.278227
2013-01-05 -2.194728 -2.536257 0.478644 0.057728
2013-01-06 -1.092031 1.249952 1.598761 -0.153423 In [83]: df.loc[dates[0]] # 作为index的日期列叫dates
Out[83]:
A -0.411674
B 0.273549
C 0.629843
D 1.881497
Name: 2013-01-01 00:00:00, dtype: float64 #---对多个维度轴axis进行选取---
In [84]: df.loc['20130102':'20130104',['A','B']]
Out[84]:
A B
2013-01-02 1.240512 0.970725
2013-01-03 -0.544326 0.545738
2013-01-04 1.044803 -0.117151 #---选取某个数值---
In [85]: df.loc[dates[0],'A']
Out[85]: -0.41167416696608039 In [86]: df.at[dates[0],'A'] # 更高效的做法
Out[86]: -0.41167416696608039多重索引的选取
index有多个维度
#这里有一个多重索引
MultiIndex(levels=[[1, 2, 3], ['count', 'mean', 'std', 'min', '5%', '10%', '15.0%', '20%', '25%',
'30.0%', '35%', '40%', '45%', '50%', '55.0%', '60.0%', '65%', '70%',
'75%', '80%', '85.0%', '90%', '95%', 'max']],
labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23]],
names=['label_1', None]) df[columnName] #选某一列,或多列(":",[,,,])
df.loc[:,columnName] #选某一列,或多列(":",[,,,])
df.loc[1,columnName] #可以直接用最外层的索引
df.loc[(1,'std'),columnName] #多层索引要用tuple。选多行用":"连接tuple。
df.loc[[(1,'std'),(2,"count")],'feature_001']
用位置选取:.iloc
.lic[],位置索引,方括号里是整数值。同样的用“,”隔开行列。
In [93]: df.iloc[3]
Out[93]:
A 1.044803
B -0.117151
C 0.874583
D 2.278227
Name: 2013-01-04 00:00:00, dtype: float64 In [94]: df.iloc[3:5,0:2]
Out[94]:
A B
2013-01-04 1.044803 -0.117151
2013-01-05 -2.194728 -2.536257 In [95]: df.iat[1,1]
Out[95]: 0.97072539301549565
**布尔索引 **Boolean Indexing
某一列大于0的数据
In [96]: df[df.A > 0]
Out[96]:
A B C D
2013-01-02 1.240512 0.970725 0.033099 1.553420
2013-01-04 1.044803 -0.117151 0.874583 2.278227
整体大于零的数据。小于0的为NaN
In [97]: df[df > 0]
Out[97]:
A B C D
2013-01-01 NaN 0.273549 0.629843 1.881497
2013-01-02 1.240512 0.970725 0.033099 1.553420
2013-01-03 NaN 0.545738 NaN 0.130738
2013-01-04 1.044803 NaN 0.874583 2.278227
2013-01-05 NaN NaN 0.478644 0.057728
2013-01-06 NaN 1.249952 1.598761 NaN
对字符型数据选取
#---isin ---
In [98]: df2 = df.copy()
...: df2['E'] = ['one', 'one','two','three','four','three']
...: df2
...:
Out[98]:
A B C D E
2013-01-01 -0.411674 0.273549 0.629843 1.881497 one
2013-01-02 1.240512 0.970725 0.033099 1.553420 one
2013-01-03 -0.544326 0.545738 -1.325810 0.130738 two
2013-01-04 1.044803 -0.117151 0.874583 2.278227 three
2013-01-05 -2.194728 -2.536257 0.478644 0.057728 four
2013-01-06 -1.092031 1.249952 1.598761 -0.153423 three In [99]: df2[df2['E'].isin(['two','four'])]
Out[99]:
A B C D E
2013-01-03 -0.544326 0.545738 -1.325810 0.130738 two
2013-01-05 -2.194728 -2.536257 0.478644 0.057728 four
使用布尔面具
In [107]: mask = df2["A"] >0 In [108]: df3 = df2[mask] In [109]: df3
Out[109]:
A B C D E
2013-01-02 1.240512 0.970725 0.033099 1.553420 ONE
2013-01-04 1.044803 -0.117151 0.874583 2.278227 THREE # 查看无重复的值:.unique()
In [101]: df2.loc[:,"E"].unique()
Out[101]: array(['one', 'two', 'three', 'four'], dtype=object)
Python数据分析_Pandas01_数据框的创建和选取的更多相关文章
- python数据分析笔记——数据加载与整理]
[ python数据分析笔记——数据加载与整理] https://mp.weixin.qq.com/s?__biz=MjM5MDM3Nzg0NA==&mid=2651588899&id ...
- Python中dataframe数据框中选择某一列非空的行
利用pandas自带的函数notnull可以很容易判断某一列是否为null类型,但是如果这一列中某一格为空字符串"",此时notnull函数会返回True,而一般我们选择非空行并不 ...
- Python数据分析--------numpy数据打乱
一.shuffle函数: import numpy.random def shuffleData(data): np.random.shufflr(data) cols=data.shape[1] X ...
- (数据科学学习手札06)Python在数据框操作上的总结(初级篇)
数据框(Dataframe)作为一种十分标准的数据结构,是数据分析中最常用的数据结构,在Python和R中各有对数据框的不同定义和操作. Python 本文涉及Python数据框,为了更好的视觉效果, ...
- Python数据分析之pandas学习
Python中的pandas模块进行数据分析. 接下来pandas介绍中将学习到如下8块内容:1.数据结构简介:DataFrame和Series2.数据索引index3.利用pandas查询数据4.利 ...
- Pandas系列(二)- DataFrame数据框
一.初识DataFrame dataFrame 是一个带有索引的二维数据结构,每列可以有自己的名字,并且可以有不同的数据类型.你可以把它想象成一个 excel 表格或者数据库中的一张表DataFram ...
- python 数据分析--pandas
接下来pandas介绍中将学习到如下8块内容:1.数据结构简介:DataFrame和Series2.数据索引index3.利用pandas查询数据4.利用pandas的DataFrames进行统计分析 ...
- Python数据分析之pandas
Python中的pandas模块进行数据分析. 接下来pandas介绍中将学习到如下8块内容:1.数据结构简介:DataFrame和Series2.数据索引index3.利用pandas查询数据4.利 ...
- Python数据分析与展示[第三周](pandas简介与数据创建)
第三周的课程pandas 分析数据 http://pandas.pydata.org import pandas as pd 常与numpy matplotlib 一块定义 d=pd.Series(r ...
随机推荐
- tiny4412 UART for C printf Demo
/************************************************************************** * tiny4412 UART for C pr ...
- 【opencv基础】imread-第二个参数
问题1: 显示的是灰色的界面,不能正常显示图像. 解决方法:在imshow之后加上waitKey即可.原因here: Note:This function should be followed by ...
- 字符串匹配--扩展KMP模板
对于一个字符串 s 以及子串 t ,扩展KMP可以用来求 t 与 s 的每个子串的最长公共前缀 ext [ i ],当然,如果有某个 ext 值等于 t 串的长度 lent ,那么就说明从其对应的 i ...
- java并发编程-Executor框架 + Callable + Future
from: https://www.cnblogs.com/shipengzhi/articles/2067154.html import java.util.concurrent.*; public ...
- bootstrap中如何控制input的宽度
☆1☆ bootstrap中如何控制input的宽度: v2版本:定义了很多class,可用在input. "input-block-level"."input-mini ...
- IBM WebSphere MQ介绍安装以及配置服务详解(转)
首先介绍一下MQ MQ消息队列的简称是一种应用程序对应用程序的通信方法.说白了也就是通过队列的方式来对应用程序进行数据通信.而无需专用链接来链接它们. MQ的通讯方式 1.数据报的方式 Datagra ...
- apache配置禁止访问某些文件/目录
我们来看俩段通常对上传目录设置无权限的列子,配置如下: 代码如下: ? 1 2 3 4 5 6 <Directory "/var/www/upload"> <Fi ...
- 和为 s 的两个数字(和为 s 的连续正数序列)
题目 输入一个递增排序的数组和一个数字 s,在数组中查找两个数,得它们的和正好是 s.如果有多对数字的和等于 s,输出任意一对即可 思路 我们先在数组中选择两个数字,如果它们的和等于输入的 s,我们就 ...
- saltops 安装及相关环境安装
本次布署测试环境 阿里云 Centos 7.3 1.安装nginx,这里采用yum 安装方式 A.yum install nginx B.创建开机启动 systemctl enable nginx.s ...
- bzoj1055玩具取名
区间dp.记录可行性即可. #include<iostream> #include<cstdio> #include<cstring> using namespac ...