pandas
文章目录
其它
dir(变量名)# 查询该变量能使用的函数
pd.set_option('display.max_rows',10)
pd.set_option('display.max_columns'10)
pd.__version__ # 查看包的版本
!type f:\test\News\DataAnalyst.csv # 查看文件内容、格式
!type f:\test\demo.json
!dir # 查看目录下,文件名称
list(open('demo.csv')) # 打开查看文件
Series
- Sries最重要的一个功能是:它在算术运算中会自动对齐不同索引的数据
属性
- .values
- .index
- .name
- .index.name
创建
pd.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
s = {'a':'A','c':'d','b':'B'}
pd.Series(s,index=[1,3,'a','c'])
pd.Series(np.random.randint(10,50,5,dtype=int))
pd.Series(['a','ab','v'],index=list('abc'),name='demo')
修改删除
s1['a']=
s1.iloc[0]=
s1.loc['a']=
s1.append() #返回新的Series
s1['new_index']= # 在s1上修改(添加)
del s1['index']
s1.to_dict() # 保存为tuple
pd.isnull(s1)
pd.notnull(s1)
过滤
s1[s1<100]
描述统计
- 数值型
- 分位数
s1.describe()
s1.describe(percentiles=[0.1,0.25,0.5])# 选择分位数
s1.quantile(0.5)# 分位数
s1.quantile(0.25)
- 分类统计
s.value_counts()# 每一类有多少项
-
pd.value_counts(df['col'])
-
s.pct_change()
DataFrame
-
df = pd.DataFrame()
-
返回df的每一行:
for i in df.iterrows(): print(i)
IO
-
df = pd.read_clipboard() df.to_clipboard() df.to_csv('demo.csv',index=False) df.to_json() df.to_html('demo.html') df.to_excel('demo.xlsx')
TimeSeries
pd.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs)
基础
索引对象
-
index对象是不可修改的
-
df.index[1]= -
df.index is index df.index = pd.index(np.arange(3))
-
DatetimeIndex,存储纳秒级时间戳,用numpy的达特time64类型表示
-
PeriodIndex,针对period(时间间隔)数据的特殊index
-
-
重命名
df.index.map(str.upper) df.rename(index=str.upper,columns=str.lower) df.rename(index={'ind1':'new_ind1'}, columns={'col1':'new_col1','col2','new_col2'} ) df.rename(index=‘自定义函数’)
重新索引reindex
-
Series 根据新索引重排
-
se.reindex(['index_1','index_3','index_2'])
-
如果某个索引值不存在,就引入缺失值
-
se.reindex(['index_a','index_b','index_c'],fill_value=0) # 缺失部分填充为0
-
插值处理
se.reindex(range(6),methon='ffill')
-
-
DataFrame
-
df.reindex(index=[], #用作索引的新序列 method = 'bfill', #插值填充方式,插值只能按行应用,即轴0 columns=[], fill_value = 0, #在重新索引的过程中,需要引入缺失值时使用的替代值 limit = 3, #前向或后向填充时的最大填充量 level = ,# 在MultiIndex的指定级别上匹配简单索引,否则选取其子集 )
-
df1.reindex(columns=df2.columns,fill_value=0)
-
多重索引
-
s = pd.Series(np.random.rand(6), index=[['1','1','1','2','2','2'], ['a','b','v','a','b','c']]) s.unstack() # 变为DataFrame 最内层index变为columns
丢弃drop()
-
se.drop('index_n')
-
df.drop(['index_1','index_2'])#删除行 df.drop(['col1','col2'],axis=1)#删除列
索引、选取和过滤
-
se['a'] se[1] se[2:4] #取值范围[2:4) se['a':'c'] #取值范围[a:c] se[['a','b','c']] se[[1,3]] se[se<2]
-
# 选取列 df['col1'] df[['col1','col3']] # 选取行(通过切片或布尔型数组选取行) df[:2] #前2行 df[df['col2']] #布尔型DataFrame索引 df[df<3]
索引的重复性
-
se.index.is_unique
算数运算
-
填充值
-
当一个对象中某个轴标签在另一个对象中找不到时,填充一个特殊值
-
df1.add(df2,fill_value=0) df.reindex(columns=df2.columns,fill_value=0)
-
add 加法 sub 减法 div 除法 mul 乘法
-
-
-
广播运算broadcasting
apply
-
df.apply(lambda x:x.max() - x.min()) df.apply(lambda x:x.max() - x.min(), axis =1) #axis : {0 or 'index', 1 or 'columns'
-
df.apply(pd.value_counts).fillna(0)
applymap元素级应用
-
df.applymap(lambda x:'.2f' % x)
排序
-
sort_index()
-
sort_values()
-
pd.value_counts(se.values, sort=True,#按值排序 ascending=True,#按频率技术,升序排 bins=3, #pd.cut()分箱,只适用于数字数据 dropna=True #不包括NaN的数量 )
排名
se.rank(method='first')#按出现顺序排名
se.rank(method='average')#分配平均排名
se.rank(acending=False,method='max')#使用整组的最大排名
-
df.rank(axis=1) # axis : {0 or 'index', 1 or 'columns'}
描述统计
-
df.describe() df.describe(percentiles=[0.5,0.75]) df.quantile([0.5,0.75]) df.mean(skipna=False)# 排除缺失值,默认为True df.count()#非NaN的值个数 df.idxmax(),df.idxmin()#获取极值的索引值 df.argmin(),df.argmax()#获取极值的索引位置(整数) df.sum() df.mean() df.median() df.mad()# 根据平均值计算平均绝对离差 df.var()# 方差 df.std()# 标准差 df.skew()#偏度,三阶矩 df.kurt()#峰度,四阶矩 df.cumsum()#累加 df.cummin(),df.cummax()#累计极值 df.cmprod()#累积 df.diff()#一阶差分(时间序列中) df.pct_change()# 计算百分数变化
相关性,协方差
-
df.corr()#相关系数 df.cov()#协方差矩阵
-
DataFrame与其他DataFrame、Series的相关系数
df.corrwith(series) df.corrwith(df.col1) df1.corrwith(df2,axis=1) #axis : {0 or 'index', 1 or 'columns'}, default 0
去重
se.unique().value_counts(ascending=)#去重+排序
缺失值处理
-
诊断
df.isnull().values.any() df.isnull().any() df['col'].isnull() df['col'].isnull().values.any()
-
统计
df.isnull().sum() df.isnull().sum().sum()
-
取舍
- 行
df.dropna() df.dropna(how='any') df.dropna(thresh=2)#舍弃缺失值超过2个的行
- 列
df.dropna(how='all',axis=1)#舍弃整列为NaN的列
-
填充
-
method
df.fillna(method='ffill') df.fillna(method='bfill',limit=3)
-
填充统计数据
df['col'].fillna(df['col'].mean()) df['col'].fillna(df.groupby('')[].transform('mean')) df.fillna({'col1':1,'col3':3})
-
-
内插补齐法
df.interpolate()
-
计算缺失值占比
df.isnull().sum() / df.count()
排序-去重
-
先排序
df.sort_values(by='col_1')
- 因为排序会将NaN放在最后,确保之后的去重操作不会将其他列为NaN的值保留
-
再去重
df.drop_duplicates(subset=['col_2','col_3','col_5'])
- 因为先做了col_1的排序,所以去重后的保留行中,col_1列的元素不会为NaN
- DataFrame.drop_duplicates()的用法
- 去重
DataFrame.drop_duplicates(subset=None, keep='first', inplace=False)
- subset:对应的值是列名,将这些列对应值相等的行进行去重,默认所有列
subset=['col1','col2']
- keep:删除重复项并保留第一次出现的项
'first','last',False
,False:一行都不留 - inplace:是否直接在原数据上修改
- subset:对应的值是列名,将这些列对应值相等的行进行去重,默认所有列
- 去重
map replace
-
df1 = pd.DataFrame({'城市':['BJ','SH','GZ'], '人口':[1000,2000,1500] }, index=list('abc') ) gdp_map={'BJ':1000, 'SH':2000, 'GZ':1500 } df1['GDP'] = df1['城市'].map(gdp_map)
-
根据字典给DataFrame添加新列
df['new_col']=df['字典提到的col'].map(字典)
-
用Series构建新column(推荐用map)
df['new_col'] = pd.Series([],index=) # 需注意Series中值的顺序,index要与df的一一对应
-
s.replace('要替换的值','替换为') s.replace(1,np.nan) s.replace([1,2,3],[11,22,33])
数据抽样sampling
-
.sample()
-
随机取样
-
-
DataFrame.sample(n=None, frac=None, replace=False,weights=None, random_state=None, axis=None*)
s.sample(n = 3)# 选3个随机元素 df.sample(frac = 0.1) # 随机取10%的元素 df.sample(n = 3)# 随机取3行
-
时间采样Series.resample()【详解笔记 时间序列 部分】
-
-
map
-
df.index.map(str.upper) # 不替换
-
list1=[1,2,3,4] [str(x) for x in list1] list(map(str,list1))
-
def test_map(x): return x+'_ABC' df.index.map(test_map) df.rename(index=test_map)
关联
pd.merge
-
pd.merge
pd.merge(left,right,on=,how='inner')
-
pd.merge(left,right,left_on=,right_on,suffixes=('_x', '_y')
pd.concat
-
Series
pd.concat([s1,s2]) # 上下堆叠 pd.concat([s1,s2],axis=1)# 引入column的计算,变为DataFrame
-
DataFrame
pd.concat([df1,df2]) # 上下堆叠
np.concatenate()
-
上下堆砌
np.concatenate([arr1,arr2])
-
左右连接
np.concatenate([arr1,arr2],axis=1)
combine
-
s1.combine_first(s2) # s2填充s1的NaN
df1.combine_first(df2)
apply预处理
-
df['col1'] = df['col1'].apply(str.upper)
-
def foo(line): a = line.strip().split(' ') return np.Series([a[1],a[3],a[5]]) df_new = df['col'].apply(foo) df_new.rename(columns={0:'A',1:'B',2:"C"}) df.combine_first(df_new)
分箱
-
pd.cut()
pd.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise')
分组
-
.groupby
df.groupby() df.groupby().mean() list(df.groupby()) dict(list(df.groupby()))[''] for a, b in df.groupby(): print(a),print(b) df.groupby().groups df.groupby().get_group('') df.groupby().get_group('').mean()
-
gs = df.groupby(['col1','col3']) for (name1,name2), b in gs: print(name1) print(b)
透视表
-
pd.pivot_table(df,index=, columns=, values=, aggfunc= )
By儒冠多误身 2019/04/21