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,+,-,*,/)的更多相关文章

  1. python. pandas(series,dataframe,index) method test

    python. pandas(series,dataframe,index,reindex,csv file read and write) method test import pandas as ...

  2. python pandas.Series&&DataFrame&& set_index&reset_index

    参考CookBook :http://pandas.pydata.org/pandas-docs/stable/cookbook.html Pandas set_index&reset_ind ...

  3. pandas数组(pandas Series)-(5)apply方法自定义函数

    有时候需要对 pandas Series 里的值进行一些操作,但是没有内置函数,这时候可以自己写一个函数,使用 pandas Series 的 apply 方法,可以对里面的每个值都调用这个函数,然后 ...

  4. pandas之DataFrame创建、索引、切片等基础操作

    知识点 Series只有行索引,而DataFrame对象既有行索引,也有列索引 行索引,表明不同行,横向索引,叫index,0轴,axis=0 列索引,表明不同列,纵向索引,叫columns,1轴,a ...

  5. Python Pandas -- Series

    pandas.Series class pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath ...

  6. pandas Series的sort_values()方法

    pandas Series的 sort_values() 方法能对Series进行排序,返回一个新的Series: s = pd.Series([np.nan, 1, 3, 10, 5]) 升序排列: ...

  7. python基础:如何使用python pandas将DataFrame转换为dict

    之前在知乎上看到有网友提问,如何将DataFrame转换为dict,专门研究了一下,pandas在0.21.0版本中是提供了这个方法的.下面一起学习一下,通过调用help方法,该方法只需传入一个参数, ...

  8. python 基本类型的创建方法

    1.int class int(object) | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a numbe ...

  9. pandas DataFrame的创建方法

    pandas DataFrame的增删查改总结系列文章: pandas DaFrame的创建方法 pandas DataFrame的查询方法 pandas DataFrame行或列的删除方法 pand ...

随机推荐

  1. cmake3.8X64编译opencv3.2出现opencv_ffmpeg、opencv_ffmpeg_64、ippicv_windows_20151201.zip无法下载问题解决方案

    cmake版本:cmake3.8.0 开发环境:Visual Studio 2017 x64 解决方法:1.在opencv安装目录下sources\3rdparty\ffmpeg\ffmpeg.cma ...

  2. Swift 表达式

    前言 Swift 语言使用表达式来表示程序中的最小单位,通常一个表达式是由数字.字符.运算符.变量.常量.函数调用等可以求得值的有意义的排列组成的组合. 根据组合方式的不同,表达式可以分为基本表达式. ...

  3. 【struts2】<s:url>标签

    <s:url>标签一般和超链接 <a>一起使用,用于带多个参数. <a href=" <s:url action=""> < ...

  4. 使用Unified Auditing Policy审计数据泵导出操作

    1.创建审计策略 SQL> alter session set container=pdb1; SQL> create or replace directory dumpdir as '/ ...

  5. MySQL -- Innodb是如何处理自增列的

    对于那些向带有自增列的表中插入行的语句,Innodb提供一种可配置的锁定机制,这种锁定机制可以显著提高SQL语句的可伸缩性和性能. Innodb中为了使用自增机制,自增列必须是索引的部份,从而可以使用 ...

  6. vfork 挂掉的一个问题

    在知乎上,有个人问了这样的一个问题——为什么vfork的子进程里用return,整个程序会挂掉,而且exit()不会?并给出了如下的代码,下面的代码一运行就挂掉了,但如果把子进程的return改成ex ...

  7. Struts2之数据标签(二)

    Struts2之数据标签(一):http://blog.csdn.net/u012561176/article/details/46848817 1.action标签:使用此标签能够同意在JSP页面中 ...

  8. CTreeCtrl获得鼠标点击时的节点

    原文链接: http://blog.csdn.net/lcalqf/article/details/21321923 1.添加图标 HICON icon[10]; icon[0]=AfxGetApp( ...

  9. 【转载】Hibernate之hbm.xml集合映射的使用(Set集合映射,list集合映射,Map集合映射)

    https://www.cnblogs.com/biehongli/p/6555994.html

  10. 解决sklearn 随机森林数据不平衡的方法

    Handle Imbalanced Classes In Random Forest   Preliminaries # Load libraries from sklearn.ensemble im ...