python pandas ---Series,DataFrame 创建方法,操作运算操作(赋值,sort,get,del,pop,insert,+,-,*,/)
pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包
pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的,
导入如下:
from pandas import Series,DataFrame
import pandas as pd
import numpy as np
Series可以理解为一个一维的数组,只是index可以自己改动。
类似于定长的有序字典,有Index和value。
传入一个list[]/tuple(),就会自动生成一个Series
s = pd.Series(data, index=index)
pd.Series(data,index=) index赋值必须是list类型
#ser1=Series((1,2,3,4))
#ser1=Series([1,2,3,4])
ser1 = Series({'a':1,'b':2,'c':3,'d':4})
DataFrame可以看成是以Series组成的字典,具有行索引和列索引。
DataFrame(data,columns=,index=)其中columns为列的索引,index为行的索引。index或者columns如果不进行设置则默认为0开始的整数
dict(one to many)生成一个DataFrame
data ={'pop':(1,2,3,4),#[1,2,3,4]
'state':[5,6,7,8],
'year':[2001,2003,2003,2004]}
d=DataFrame(data) #用字典创建DataFrame
print(d)
d2 = DataFrame(data,index=['one','two','three','four'])
print(d2)
d3 = DataFrame(data, index=['one', 'two', 'three', 'four'],columns=['year','pop','state'])#按指定列进行排序
print(d3)
删除:使用del或者pop(‘columns’)方法。需要注意的是所有删除的方法都会改变原来DataFrame,
而不是像其他方法一样内存当中新建一个DataFrame。pop由于弹出特定的列,会返回被弹出的列中的数值.
demo :
from pandas import Series,DataFrame
import pandas as pd
import numpy as np def seriesDemo():
#创建,(),[],{},二维的ndarray,Series,外部数据引入,比如csv, excel等
# 获取值,index,qiepian
# 运算 +,- *, /,
# 读取,
# insert,df.insert(1,'remark',df['year'])
# 删除列(del df['two'], df.pop['two']
#s = Series(5)
#ser1=Series((1,2,3,4))
#ser1=Series([1,2,3,4])
ser1 = Series({'a':1,'b':2,'c':3,'d':4})
print(ser1)
print(ser1.index)
print(ser1.values)
print(ser1[3]) print(ser1 > 2)
print(ser1[ser1 > 2])
print(ser1[ser1==2])
print(Series(ser1,['beijin','shenzheng','shanghai','guangzhou']))
print(Series([1,2,3,4], ['beijin', 'shenzheng', 'shanghai', 'guangzhou']))
#Series.values和Series.index,分别查询值和索引
print(Series[:2]) def dataframDemo(): # DataFrame:一维数据类型进行创建、二维ndarray创建、外部输入读取文件等手段,如csv、excel等文件
data ={'pop':(1,2,3,4),#[1,2,3,4]
'state':[5,8,7,8],
'year':[2001,2003,2003,2004]} #创建
d=DataFrame(data) #用字典创建DataFrame
print(d)
d2 = DataFrame(data,index=['one','two','three','four'])
print(d2)
d3 = DataFrame(data, index=['one', 'two', 'three', 'four'],columns=['year','pop','state'])#按指定列进行排序
print(d3)
print('*'*20)
print(d3['year']) #get one columns #通过类似字典的取值方式,我们可以取到一个Series,根据列索引 #loc()loc操作获取行,loc操作需要行的标签,iloc()iloc操作根据行列获取数据
print(d3.ix[0]) #get one row
d3['newcolumns']='2009'#给一列赋单值
print(d3)
d3['newcolumns']=np.arange(1,5)#给一列赋yizu值 arange(4)
print(d3)
d3.ix['one'] = '2000' # 给一row赋单值
print(d3)
d3.ix['one'] = np.arange(1,5) # 给一row赋单值
print(d3) val = Series([1,2,3],index=['two','three','four']) #赋值一个Series,进行df精确匹配,其他值填充为NaN
d3['four']=val
print('*'*30)
print(d3) #insert
d3.insert(1, 'remrk', d['year'])
print(d) #get top and botton 5 row
print(d3.head()) #查询前几行的数据默认为5行
print(d3.tail()) #查看后几行书,默认为5行
print('*' * 30) #sort index,value
print(d3.sort_index(axis=1,ascending=False))
print(d3.sort_values(by='year', ascending=False))
print(d3[0:2])
print(d3['year'])
print(d3.loc[['one','two'],['year','pop']]) #by indexname, columns name get data 标签
print(d3.iloc[0:1,0:1]) #by qie pian get data 绝对位置
print(d3[d3 >3])
print(d3[d3['year']==1])
print(d3[d3['year'].isin([1,2003])]) #assign操作会把结果储存在DataFrame中
d4 = d3.assign(remark=d['pop'] + 10)
print(d4)
#del columns
del d3['four'] # del用于删除一列 #del Nan
print(d3.dropna(axis=1,how='any'))
print(d3.dropna(axis=1, how='all'))#axis为0/1参数;how为any/all参数,any是存在NaN就把对应的整行/列删除,all是全部为NaN才把对应的整行/列删除 #对于NaN的处理:
print(d3.fillna('0')) #将所有NaN赋值为0
print(d3.isnull()==True) #是否为null #合并:concat,merge,append
print(pd.concat([d3,d3],ignore_index=True)) #多个DataFrame进行合并,ignore_index是boolean值,用来确定要不要重新对index从0开始赋值
print('*'*30)
#print(pd.merge([d3, d3],on=True))
print(d3.append(d3,ignore_index=True)) #部添加一个object,可以是DataFrame也可以是Series,ignore_index就是用来确定要不要重新对index从0开始赋值,这个比较好理解。 #分组:groupby
print('*groupby'*10)
d4=d3.groupby(by='year',axis=0,as_index=True) #按照一些规则将数据分为不同的组;对于每组数据分别执行一个函数;将结果组合到一个数据结构中。as_index指的是分组依据是否作为索引存在,
# 有多个分组依据时,会合并成一个tuple,作为一列
print(d4.aggregate(np.max)) #通过aggregate(arg)方法可以打印分好组的group,arg可以为dict类型或者list类型。
d5 = d3.groupby(['year','pop'],as_index=False)
d6 = d5.aggregate(np.sum)
print('d6',d6) print('agg',d3.groupby(['year'])['pop'].agg([np.mean])) #agg(arg)方法对分好组的group进行计算
# d = DataFrame(np.random.randn(4, 2))
# print(d) def pandreadcsvDemo():
cs = pd.read_csv(r'C:\360安全浏览器下载\2016517_118269_TravelRecords.xls',encoding='UTF-8')
data = DataFrame(cs,columns=['name','date'])
python pandas ---Series,DataFrame 创建方法,操作运算操作(赋值,sort,get,del,pop,insert,+,-,*,/)的更多相关文章
- python. pandas(series,dataframe,index) method test
python. pandas(series,dataframe,index,reindex,csv file read and write) method test import pandas as ...
- python pandas.Series&&DataFrame&& set_index&reset_index
参考CookBook :http://pandas.pydata.org/pandas-docs/stable/cookbook.html Pandas set_index&reset_ind ...
- pandas数组(pandas Series)-(5)apply方法自定义函数
有时候需要对 pandas Series 里的值进行一些操作,但是没有内置函数,这时候可以自己写一个函数,使用 pandas Series 的 apply 方法,可以对里面的每个值都调用这个函数,然后 ...
- pandas之DataFrame创建、索引、切片等基础操作
知识点 Series只有行索引,而DataFrame对象既有行索引,也有列索引 行索引,表明不同行,横向索引,叫index,0轴,axis=0 列索引,表明不同列,纵向索引,叫columns,1轴,a ...
- Python Pandas -- Series
pandas.Series class pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath ...
- pandas Series的sort_values()方法
pandas Series的 sort_values() 方法能对Series进行排序,返回一个新的Series: s = pd.Series([np.nan, 1, 3, 10, 5]) 升序排列: ...
- python基础:如何使用python pandas将DataFrame转换为dict
之前在知乎上看到有网友提问,如何将DataFrame转换为dict,专门研究了一下,pandas在0.21.0版本中是提供了这个方法的.下面一起学习一下,通过调用help方法,该方法只需传入一个参数, ...
- python 基本类型的创建方法
1.int class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a numbe ...
- pandas DataFrame的创建方法
pandas DataFrame的增删查改总结系列文章: pandas DaFrame的创建方法 pandas DataFrame的查询方法 pandas DataFrame行或列的删除方法 pand ...
随机推荐
- 【jsp】JSP中page指令isThreadSafe
<%@ page isThreadSafe="true|false" %> 默认值为true isThreadSafe=false模式表示它是以Singleton模式运 ...
- Postgresql: UUID的使用
默认安装的 Postgresql 是不带 UUID 函数的,为了生成一个 UUID,我们必须装载它到数据库中. CREATE EXTENSION "uuid-ossp"; 然后就可 ...
- SpringMVC整合Mongodb开发,高级操作
开发环境: 操作系统:windows xpMongodb:2.0.6依 赖 包:Spring3.2.2 + spring-data-mongodb-1.3.0 + Spring-data-1.5 + ...
- Oracle 12C -- CDB的启动过程
以启动DB12为例子 $ sqlplus '/as sysdba' SQL*Plus: Release Production on Sun Nov :: Copyright (c) , , Oracl ...
- 一个“蝇量级” C 语言协程库
协程(coroutine)顾名思义就是“协作的例程”(co-operative routines).跟具有操作系统概念的线程不一样,协程是在用户空间利用程序语言的语法语义就能实现逻辑上类似多任务的编程 ...
- MySQL 两个数据库表中合并数据
两个数据库表中合并数据 如果有 t1 和 t2 两个数据库表格,它们两个对应的字段是相同的.如何将 t2 的数据插入到t1中去呢? insert into t1 select * from t2 ...
- [转载]java日志框架log4j详细配置及与slf4j联合使用教程
一.log4j基本用法 首先,配置log4j的jar,maven工程配置以下依赖,非maven工程从maven仓库下载jar添加到“build path” 1 2 3 4 5 <dependen ...
- Java常考面试题(二)
序言 昨天刚开始的”每日5题面试“这类文章,感觉还不错,把一些平常看似懂了的东西,弄清楚了.就像什么是虚拟机?这个问题,看起来知道,但是要说出个所以然来,又懵逼了,经常回过头来看看做过的面试题,试着用 ...
- 未能为数据库 '*'中得对象'*'分配空间,因文件组'PRIMARY'已满
服务器使用mssqlserver2005,最近经常出现无法新增信息错误,查看日志,发现严重错误提示,内容大致为: 无法为数据库 'weixin_main' 中的对象 'dbo.wx_logs'.'PK ...
- 每日英语:American Cities May Have Hit 'Peak Office'
Despite some hype and a few regional exceptions, the construction of office towers and suburban offi ...