首页 python和人工智能正文

pandas 基础教程

pandas 结合 numpy  matplotlib 的优势,专门用于数据挖掘的开源python库。

pandas 3种结构:

    DataFrame:  

            创建:  pd.DataFrame()      index  行索引  columns  列索引

            属性:   shape  index  columns  values  T  head() tail()

            索引的设置:   必须全部设置,不能只修改一个   reset_index(drop=false)  重设索引   set_index("")  设置新的索引

    multiindex,panel:

            multiindex:  df.index    df.index.names

            panel:  已经取消

    series: 创建:  pd.Series(np.arange()     pd.Series([],index=[])   pd.Series({})

                   属性:  index   value


基本数据操作:

        去列:

                data2=data2.drop(['关键词ID','推广单元ID','推广计划ID'],axis=1)

        索引操作:  loc  iloc     

                data2.loc[0:3,'消费'] # 先行后列  字符

                data2.iloc[0:3,0:3]   # 先行后列  数字下标    

                data2.iloc[0:3,data2.columns.get_indexer(['日期','消费'])]  # columns.get_indexer    np  取消 ix

                data2.loc[data.index[0:3],['日期','消费']]   #  data.index  转字符


        赋值:data['']=*  data.close=**      data2['商桥转化']=0   

        排序: sort_values()    sort_index()

                data2.sort_values(by='消费',ascending=False).head() # by  可以数组 多字段排序


运算:

        算术运算: df[''].add()  .sub()

        逻辑运算: df.query()    df[''].isin([])    > <  | &      

                data2[(data2['展现'] >2) & (data2['消费'] >5)].head()

                data2.query('展现>2 & 消费>5').head()

                data2[data2['展现'].isin([1,2,3])].head()


        统计运算: data2.describe()      sum mean median  min max  mode  abs  prod  std var idxmax  idxmin

        累积统计函数: cumsum()  cummax()  cummin() cumprod()

                xf=data2['消费']

                cumxf=xf.cumsum()

                import matplotlib.pyplot as plt

                cumxf.plot()

                plt.show()


        自定义函数:  apply(func,axis=0)       

                data2[['展现','消费']].apply(lambda x: x.max()-x.min(),axis=0)


        画图:data2['消费'].plot(kind='bar',figsize=(20,8),fonttize=18) # data2.plot   kind: line bar hist pie scatter   barh

               

文件读取和存储:

        pd.read_csv('',usecols=[])    df.to_csv('',columns=[],index=,mode=,hreader=)

        pd.read_json()   df.to_json()


        # data = pf.read_csv('./1.csv',usecols=['xx','xx'])

        # data2.to_csv('./save.csv',colums=['xx'])


缺失值:

        判断:  isnull() notnull()    删除 dropna()   替换 fillna()

        # data2.isnull()  # notnull  np.any(data.isnull())

        # data2.dropna()  

        # data2.fillna(value,inplace=True)

        # data2.replace(to_replace='?',value=np.nan)  替换其他非标准的为 nan


高级处理:

        数据离散化:

            

            # 数据  分类   类转列  0 1

            q=pd.qcut(data2['消费'],10)   //分10份

            q.value_counts()


            r2=pd.cut(data2['消费'],bins=[0,5,10,15,20,40,100])  //按区割分

            r2.value_counts()

        

        one hot 编码 

            jedm=pd.get_mmies(r2,prefix='je_')


        数据合并    

            pd.concat([data2,jedm],axis=1).head()


        merge:

            left=pd.DataFrame({'id':[1,2,3,4,5],'khxm':['小明','小张','赵云','马超','曹操']})

            right=pd.DataFrame({'khid':[1,2,3,4,5,3],'date':['2020-01-01','2020-09-01','2020-06-23','2020-03-23','2020-03-03','2020-07-20'],'je':[200,400,567,562,358,345]})

            pd.merge(right,left,how='left',left_on='khid',right_on='id')   # left  right  outer inner

            # from a left join b on a.id=b.khid


        交叉表 透视表     

                data3=data2.set_index('日期')

                data3.head()

                time=pd.to_datetime(data3.index)

                time.isocalendar().day  # week  weekday

                data3['d']=np.where(data3['消费']>10,1,0)

                data3.head()

                data3['消费'].plot()

                

                count=pd.crosstab(data3['展现'],data3['消费'])  

                sum=count.sum(axis=1)

                per=count.div(sum,axis=0)

                per.plot(kind='bar',stacked=True)

                pd.pivot_table(data2,index=u'推广计划')


        分组 聚合

            data2.groupby(['推广计划']).mean()

            st=data2.groupby(['推广计划']).count()

            st['日期'].sort_values(ascending=False)[:3] # 排序 取前面几个



代码示例:

import pandas as pd

import numpy as np

stockarr = np.random.normal(0,1,[8,10])

# frame 化

stock = pd.DataFrame(stockarr)

# 行索引

stock_code=['pp'+str(i) for i in range(stock.shape[0])]

# 列索引

date=pd.date_range(start='2020-11-01',periods=stock.shape[1],freq='B')  # freg 递进  B  跳过周末

# 加行索引 再 frame  其实不需要弄两次   第一次只是为了 得到shape

stock_c = pd.DataFrame(stockarr,index=stock_code,columns=date)




df=pd.DataFrame({'mouth':['J','F','A'],'xx':[100,20,300],'yy':[35,459,609]})

df.set_index(keys='xx')

df.set_index('mouth')





版权声明本文仅代表作者观点,不代表本站立场。本文系作者授权发表,未经许可,不得转载。图文来源网络,侵权删!

搜索