python pandas 模块

一个开源数据分析的库,它提供的数据结构DataFrame极大的简化了数据分析过程中一些繁琐操作。

导入数据:

import pandas
csv_df=pandas.read_csv(
'D:\\zzj\\11_programfile\\learn\\file\\pandas\\csv_test.csv') #f返回一个DataFrame
excel_df=pandas.read_csv(
'D:\\zzj\\11_programfile\\learn\\file\\pandas\\excel_test.xls')
csv_df0=csv_df.ix[
0] #获取第一行数据
print(csv_df0)

导出数据:

df.to_excel('excel.xlsx', sheet_name='mysheet1')

df.to_csv('cvs1.csv')

系列:Serlies

系列是具有均匀数据的一维数组结构,;特点:均匀数据、尺寸大小不变、数据的值可变

s=pandas.Series([1,2,3])

数据帧 DataFrame

用列表定义:

df=pandas.DataFrame([[1,2,3],[4,5,6],[7,8,9]]);
df.index=[
'row1','row2','row3'] #定义行标题,默认 012……
df.columns=['col1','col2','col3'] #定义列标题,默认 01……

row_a=df.ix[0:2] #获取第01
row_b=df.ix['row1':'row2'] #获取第01
col_a=df['col1'] #获取第col1
col_b=df[['col1','col3']]#获取 col1col3
cut_a=df.ix[0:2,['col1','col3']] #获取第01行的col1col3

df['col4']=4 #增加列
del df['col4'] #删除列

head=df.head(5)#获取前5行值
tail=df.tail(3)#获取后3行值
index=df.index 查看行索引
col=df.columns #查看表头
df.values #转化为数组格式
dim=df.shape #查看维度信息

info=df.info()#数据表基本信息(维度、列名称、数据格式、所占空间等)

datatype=df.dtypes

datatype=df['col1'].dtype
unique=df['col1'].unique() #查看某列的唯一值
df.fillna(value=0) #用指定值填充空值
desc=df.describe()#查看数据整体概况,和、平均值、最大、最小等
t=df.T #转置
df_sort_by_index=df.sort_index(axis=1, ascending=False)

df_sort_by_value=df.sort_values(by=['col2'])#排序
df[‘col1’].astype('int') #转换列类型
df_drop=df['col1'].drop_duplicates()#删除重复值
df_replace=df['col1'].replace(1,0)#替换
df_inner=pandas.merge(df,df1,how='inner') #内连接 

df_left=pandas.merge(df,df1,how='left')    #左连接    #

df_right=pandas.merge(df,df1,how='right')#右连接

df_outer=pandas.merge(df,df1,how='outer')  #全连接
df['group'] = numpy.where(df['col1'] > 1,'high','low')
df_query=df.query('col1==1') #按条件查询
cnt=df.groupby('col1').count()#

cnt=df.groupby('col1')['col2'].count()#按指定字段(col2)进行计数
cnt.groupby(['col1','col2'])['col3'].count()
df_inner.sample(n=6, replace=False)
df_sample=df.sample(n=2, replace=False)#采样 replace:是否放回
cov=df['col1'].cov(df['col2']) #计算两列的协方差
cov=df.cov() #所有字段间的协方差
corr1=df['col1'].corr(df['col2']) #相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关

corr=df.corr()

日期:

datelist = pandas.date_range('2016/01/21', periods=5,freq='M')
datelist = pandas.bdate_range('2018/07/03', periods=5)#不包括周六、周日
cat=pandas.Categorical(['a','b','c','a','b','c','d'], ['c', 'b', 'a'],ordered=True) #创建分类

检查缺失值

df.isnull()

df['name'].isnull() #检查缺失值

df['name'].notnull() #检查非缺失值

df['name'].isnull().values.any()#指定列是否存在缺失值

df.isnull().any() #各个列是否存在缺失值

df.isnull().values.any() #整个dataframe事发后存在缺失值

df['name'].isnull().sum() #指定列有多少缺失值

df.isnull().sum().sum() #整个dataframe有多少缺失值

分类:

a=pandas.Categorical(["test","train","test","train"])

时间方法:

a=pandas.Timestamp('20180701')
索引类型:
dates=pandas.date_range('20130101', periods=6)

猜你喜欢

转载自blog.csdn.net/henku449141932/article/details/81188676