文章目录
1.删除无用的列
df.drop(labels='列名',axis=1,inplace=True) #inplace=True代表替换原表
2.数据类型转换成时间序列类型
df['列名'] = pd.to_datetime(df['列名'])
3.将某列做为原始数据的行索引
df.set_index(df['列名'],inplace=True)
4.定位条件
df.loc[(df['close']-df['open'])/df['open']>0.03]
df.loc[df['列名'] =='值']
indexs = df.loc[df['state/region'] =='USA'].index #获取索引
abb_pop.loc[indexs,'列名'] ='值'
abb_pop_area.query('列名== "值" & 列名==值') #条件查询
5.计算滚动均值
如:计算5日均值,滚动数据取值
ma5 = df['列名'].rolling(5).mean()
6.pandas分组
df['target']=np.where(df['score']>60 ,'及格','不及格')
df['rank'] = pd.cut(df ['score'],bins=[0,60,75,85,100],labels=['不及格','及格','良好','优秀'],right=True)
df = DataFrame({'item':['Apple','Banana','Orange','Banana','Orange','Apple'],
'price':[4,3,3,2.5,4,2],
'color':['red','yellow','yellow','green','green','green'],
'weight':[12,20,50,30,20,44]})
df.groupby(by='item') #对不同种类的水果进行分组
#查看分组情况
df.groupby(by='item').groups
#计算出每一种水果的平均价格
df.groupby(by='item').mean()['price'] #不推荐
df.groupby(by='item')['price'].mean() #推荐
#数据汇总:将水果的平均价格汇总到源数据中
mean_price = df.groupby(by='item')['price'].mean()
mean_price
7.pandas处理空值
df.notnull() #返回false代表为空,True不为空
df.notnull().all(axis=1) #all,false表示改行存在空值
df.loc[df.notnull().all(axis=1)] #定位不包含空值的行
df.loc[~df.isnull().any(axis=1)] #定位不包含空值的行
df.isnull() #为空返回True,不为空返回False
df.dropna(axis=0) #将元数据中存在空值的行数据删除,axis=1即删除列
df.fillna(value='666') #将空填充
df.fillna(method='ffill',axis=0) #向前填充
df.fillna(method='bfill',axis=0) #向后填充
df.fillna(method='ffill',axis=0).fillna(method='bfill',axis=0) #向前填充一次,再向后填充一次
8.pandas处理重复值
df.drop_duplicates()
9.pandas处理异常值
如:定位大于两倍标准差的行
df.loc[~(df['C']>twice_std)]
10.python生成日历
乱入,哈哈
import calendar
# 输入指定年月
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
# 显示日历
print(calendar.month(yy,mm))
11.pandas级联操作
pd.concat((df1,df1),axis=1) #匹配级联
pd.concat((df1,df2),axis=0) #不匹配级联
pd.concat((df1,df2),axis=0,join='inner') #不匹配级联,inner join
pd.concat((df1,df2),axis=0,join='outer') #不匹配级联,outer join
df1.append(df2)
12.pandas合并操作
pd.merge(df1,df2,on='列名')
pd.merge(df3,df4) #不使用on指明合并条件则默认使用两张表共有的公共的列作为条件合并
df3 = pd.merge(df1,df2,left_on='df1列名',right_on='df2列名',how='outer')
13.pandas数据排序
DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
#by:str or list of str;如果axis=0,那么by="列名";如果axis=1,那么by="行名"。
#axis:{0 or ‘index’, 1 or ‘columns’}, default 0,默认按照列排序,即纵向排序;如果为1,则是横向排序。
#ascending:布尔型,True则升序,False降序
#inplace:布尔型,是否用排序后的数据框替换现有的数据框。
#kind:排序方法,{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’。
df.sort_values(by='列名',ascending=False)
14.pandas生成随机数
df = DataFrame(data=np.random.randint(0,100,size=(5,6))) #生成5行6列数值范围再0到100之间的随机矩阵
15.pandas替换操作
df.replace(to_replace=8,value='eight') #单值替换
df.replace(to_replace={8:'eight',11:'666111'}) #多值替换
df.replace(to_replace={3:74},value=7744) #指定列的替换操作
16.pandas映射操作
dic = {
'name':['张三','李四','张三'],
'salary':[15000,20000,15000]
}
df = DataFrame(data=dic)
dic = {
'张三':'Tom',
'李四':'Jerry'
} #映射关系表:指定好了一一的映射关系
df['e_name'] = df['name'].map(dic)
#map是Series的方法,只能被Series调用
17.python透视表
import pandas as pd
import numpy as np
df = pd.read_csv('../data/透视表-篮球赛.csv',encoding='utf8')
df.pivot_table(index=['对手','主客场'])
df.pivot_table(index=['主客场','胜负'],values=['得分','篮板','助攻'])
df.pivot_table(index=['主客场','胜负'],values=['得分','篮板','助攻'],aggfunc='sum')
df.pivot_table(index=['主客场','胜负'],aggfunc={'得分':'sum','篮板':'mean','助攻':'max'})
#获取所有队主客场的总得分
df.pivot_table(index='主客场',values='得分',aggfunc='sum')
#获取每个队主客场的总得分(在总得分的基础上又进行了对手的分类)
df.pivot_table(index='主客场',values='得分',columns='对手',aggfunc='sum',fill_value=0)
18.pandas交叉表
df = DataFrame({'sex':['man','man','women','women','man','women','man','women','women'],
'age':[15,23,25,17,35,57,24,31,22],
'smoke':[True,False,False,True,True,False,False,True,False],
'height':[168,179,181,166,173,178,188,190,160]})
pd.crosstab(df.sex,df.smoke) #求出各个性别抽烟的人数
pd.crosstab(df.age,df.smoke) #求出各个年龄段抽烟人情况
最近都没有好好的记录,批评自己一下,还是要记得记录,要学的还有很多很多,要记下来才能用呀!也要多出去走走,也要好好运动,好好背单词!