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. 【Visual Studio】Visual C# 中XML注释的使用(含注释在开发时显示换行)

    为函数方法注释说明要用到 xml 语句 <summary> 段落说明 </summary> .<para> 新段示例说明 </para>.<par ...

  2. Windows 重装系统-用户转移User和Program Files 文件夹

    原文地址:https://blog.csdn.net/sinat_38799924/article/details/74059037 重装系统时为了让系统数据保持可用我们需要做一些备份处理.比如用户数 ...

  3. MySQL Cluster

    MySQL Cluster MySQL集群一个非共享(shared nothing).分布式.分区系统,使用同步复制机制提供高可用和高性能. MySQL集群使用的是NDB引擎.NDB存储引擎会在节点间 ...

  4. Python 文件 writelines() 方法

    概述 Python 文件 writelines() 方法用于向文件中写入一序列的字符串. 这一序列字符串可以是由迭代对象产生的,如一个字符串列表. 换行需要制定换行符 \n. 语法 writeline ...

  5. sublime 技巧与快捷键篇

    技巧大全:https://www.zhihu.com/question/24896283   项目排除文件夹,更便于ctrl + p的搜索,比如可恶的node_modules "folder ...

  6. TDD 与 BDD 仅仅是语言描述上的区别么?

    当然不是了,通过这个问题,我顺便跟大家聊聊 ATDD,TDD,BDD3者的区别,方便大家有一个清晰的认识和了解. ATDD: Acceptance Test Driven Development(验收 ...

  7. 如何在Android Studio中添加注释模板信息?

    如何在Android Studio中添加注释模板信息? 在开发程序的时候,我们一般都会给文件自动添加上一些关于文件的注释信息,比如开发者的名字,开发的时间,开发者的联系方式等等.那么在android ...

  8. unity, ugui toggle, dynamic bool

    假设Canvas_debugControl.cs有一个函数 public void showNextSceneButton(bool value){ ... } 欲将其添加到一个ugui toggle ...

  9. js判断是否IE浏览器

    //ie? if (!!window.ActiveXObject || "ActiveXObject" in window){ //是 alert(1); }else{ //不是 ...

  10. activiti Task

    UserTask ScriptTask ServiceTask MailTask ManualTask ReceiveTask BusinessRuleTask callActivity