Python data science two pandas basic

from pandas import Series
import pandas as pd
s=Series([1,2,'ww','tt'])
s

#series可以自定义索引
s2=Series(['wangxing','man',24],index=['name','sex','age'])
#可以重新赋值
s2['name']='wudadiao'
s2['wife']=None
##类似于dict字典
info={
    'name':'无大招',
    'age':24,
    'gender':'man'
}
s3=Series(info)
s3.isnull()判断是否为空
#对于索引的名字是可以重新定义的
s3.index=['a','b','c',"D"]
s3
#但是要对于所有的索引重新赋值
#dataframe是一种二维数组的数据结构,可以通过column和index来确定它的值
from pandas import Series,DataFrame
data={"name":['goole','baidu','sogou'],"marks":[1,2,3],"price":[3,2,1]}
f1=DataFrame(data)

f2=DataFrame(data,columns=['name','marks','price'],index=['a','b','c'])
f2#索引也能够自定义
new_data={'name':{'first':'Python','second':'Java'},'marks':{'first':1,'second':2}}
f3=DataFrame(new_data)
f3#使用字典套字典的形式将索引给进去
f3['name']#使用索引指定不了行???,就是只能对列进行操作,截取的时候只能前几行
f3.head(1)#对行进项操作的时候能进行操作
f3['name']['first'] #col index进行指定,也就是说列名col比较高的意思

总结:

------数据查看----------
# 查看前5行,5为数目,不是索引,默认为5
data.head()
# 查看最后6行,6为数目,不是索引,默认为5
data.tail(6)
# 查看数据的形状
data.shape
# 查看数据的列数,0为行1位列
data.shape[1]
# 查看所有的列名
data.columns
# 查看索引
data.index
# 查看每一列数据的类型
data.dtypes
# 查看数据的维度
data.ndim
--------------数据索引-----------------
# 取出单独某一列
X = data['X']
# 取出多列
XY = data[['X','Y']]
# 取出某列的某一行
data['X'][1]
# 取出某列的某几行
data['X'][:10]
# 取出某几列的某几行
data[['X','Y']][:10]


# loc方法索引
'''
DataFrame.loc[行名,列名]
'''
# 取出某几列的某一行
data.loc[1,['X','月份']]
# 取出某几列的某几行(连续)
data.loc[1:5,['X','月份']]
# 取出某几列的某几行(连续)
data.loc[[1,3,5],['X','月份']]
# 取出 x ,FFMC ,DC的0-20行所有索引名称为偶数的数据
data.loc[range(0,21,2),['X','FFMC','DC']]


# iloc方法索引
'''
DataFrame.iloc[行位置,列位置]
'''
# 取出某几列的某一行
data.iloc[1,[1,4]]
# 取出列位置为偶数,行位置为0-20的偶数的数据
data.iloc[0:21:2,0:data.shape[1]:2]


# ix方法索引
'''
DataFrame.ix[行位置/行名,列位置/列名]
'''
## 取出某几列的某一行
data.ix[1:4,[1,4]]
data.ix[1:4,1:4]

-----------------时间提取------------------
# 时间类型数据转换
data['发生时间'] = pd.to_datetime(data['发生时间'],format='%Y%m%d%H%M%S')

# 提取day
data.loc[1,'发生时间'].day
# 提取日期信息新建一列
data['日期'] = [i.day for i in data['发生时间']]

--------------Groupby对象常见方法----------------

Grouped对象的agg方法:

Grouped.agg(函数或包含了字段名和函数的字典)

# 第一种情况
group[['年龄','工资']].agg(min)

# 对不同的列进行不同的聚合操作
group.agg({'年龄':max,'工资':sum})

# 上述过程中使用的函数均为系统math库所带的函数,若需要使用pandas的函数则需要做如下操作
group.agg({'年龄':lambda x:x.max(),'工资':lambda x:x.sum()})

Grouped.apply(函数操作)

只能对所有列执行同一种操作

group.apply(lambda x:x.max())

----------Grouped对象的transform方法(这个不常用????)-------------------

grouped.transform(函数操作)

transform操作时的对象不再是每一组,而是每一个元素

# 每一空添加字符
group['年龄'].transform(lambda x: x.astype(str)+'岁').head()

# 组内标准化
group1['工资'].transform(lambda x:(x.mean()-x.min())/(x.max()-x.min())).head()

猜你喜欢

转载自blog.csdn.net/qq_37312720/article/details/84026715