Pandas基础操作

    科技2022-07-12  133

    Pandas基础

    文章目录

    Pandas基础一、Series二、DataFrame三、索引值四、索引和选取loc和iloc函数讲解 五、行和列的操作map、apply、applymap函数讲解Pandas的函数应用、层级索引、统计计算 六、pandas数据可视化1.使用series绘制线性图2.使用DataFrame绘制线型图3.使用series绘制柱状图4.使用DataFrame绘制柱状图5.使用DataFrame的hist方法生成直方图 七、pandas文件操作八、pandas数据清洗与整理1.数据清洗2.重复数据duplicated,drop_duplicates函数讲解3.替换值4.虚拟变量pandas的get_dummies函数讲解5.数据合并和重塑merge函数讲解concat函数讲解6.数据重塑stack和unstack函数讲解 八、综合案例——小费数据集

    一、Series

    Series讲解

    from pandas import Series,DataFrame import pandas as pd obj = Series([1, -2, 3, -4]) #自动生产索引与之对应 type(obj) #查看series类型 obj2 = Series([1, -2, 3, -4], index=['a', 'b', 'c', 'd']) #生成数组,指定索引为a,b,c,d obj2.values #输出数组的值 obj2.index #输出数组的索引 obj2[2] #索引数组的第3个值 obj2[['c']] #输出索引为c的值 obj2['c'] = 23 #改索引为c的值为23 obj2[obj2 < 0 ] #输出所有小于0的数据 obj2 * 2 #给obj2数组所有数据×2 np.abs(obj2) #用numpy的abs函数使数组所有数据绝对值 data = { '张三':92, '李四':78, '王五':68, '小明':82 } obj3 = Series(data) #输出数组 obj4 = Series(data, index=names) #按索引名输出数组 obj4.name = 'math' obj4.index.name = 'students' #确定数组名和索引名

    二、DataFrame

    import numpy as np from pandas import Series,DataFrame import pandas as pd data = { 'name':['张三', '李四', '王五', '小明'], 'sex':['female', 'female', 'male', 'male'], 'year':[2001, 2001, 2003, 2002], 'city':['北京', '上海', '广州', '北京'] } df = DataFrame(data) #用DataFrame将数组转化为表格的形式 df = DataFrame(data, columns=['name', 'sex', 'year', 'city']) #指定标签(列)值 df = DataFrame(data, columns=['name', 'sex', 'year', 'city'],index=['a', 'b', 'c', 'd']) #指定索引值和标签值 'sex' in df.columns #判断数据是否在标签中 'f' in df.index #判断数据是否在索引中

    三、索引值

    obj = Series([1, -2, 3, -4], index=['b', 'a', 'c', 'd']) #生成数组,设置索引值 obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e']) #重新索引,若索引值无对象,则输出NaN obj2 = obj.reindex(range(6),method='ffill') #向前填充 df2 = df.reindex(['a', 'b', 'c', 'd'],fill_value=0.0) #重新索引,并将缺失值改为0.0 df3 = df2.reset_index(drop=True) #重置索引,不想保留原来的index,使用参数 drop=True,默认 False。 df2 = df.set_index('name') #将DataFrame 中的列转化为行索引

    四、索引和选取

    loc和iloc函数讲解

    obj[['a','c']] #选取索引为a和c的值 obj['a':'c'] #选取索引从a到c的值 df[['city','sex']] #选取标签为city和sex的数组数据 df2.loc['张三'] #选取标签为张三的数据 df2.iloc[1] #选取索引为1的数据 df2[(df2['sex'] == 'female') & (df2['city'] == '北京')] #交集

    五、行和列的操作

    map、apply、applymap函数讲解

    Pandas的函数应用、层级索引、统计计算

    new_data = { 'city':'武汉', 'name':'小李', 'sex':'male', 'year':2002 } df = df.append(new_data,ignore_index=True) #新加入一行数据,忽略索引值 new_df = df.drop(2,axis=0) #删除行 new_df = new_df.drop('class',axis=1) #删除列 new_df.rename(index={3:2,4:3},columns={'math':'MATH'},inplace=True) #inplace可在原数据上修改 obj1.sort_index() #升序 obj1.sort_index(ascending=False) #降序 obj1.sort_values(ascending=False) #按值降序排列 df2.sort_values(by='b',ascending=False) #以列b的值来排列,降序排列 df.describe() #输出数组基本统计量 obj.unique() #返回数组的所有唯一值 obj.value_counts() #输出每个值出现次数 obj = Series(np.random.randn(9), index=[['one','one','one','two','two','two','three','three','three'], ['a','b','c','a','b','c','a','b','c']]) #2个索引,一个大索引、一个小索引 obj[:,'a'] #内层选取 df = DataFrame(np.arange(16).reshape(4,4), index=[['one','one','two','two'],['a','b','a','b']], columns=[['apple','apple','orange','orange'],['red','green','red','green']]) #DataFrame格式化数组(2类索引的数组) df.swaplevel(0,1) #交换内层与外层索引 df.sum(level=0) df.sum(level=1,axis=1)

    六、pandas数据可视化

    1.使用series绘制线性图

    import numpy as np from pandas import Series,DataFrame import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt #导入matplotlib库 %matplotlib inline #魔法函数 s = Series(np.random.normal(size=10),index=['a','b','c','d','e','f','g','h','i','j']) s.plot() plt.show() #绘制线型图

    2.使用DataFrame绘制线型图

    df = DataFrame({'normal': np.random.normal(size=100), 'gamma': np.random.gamma(1, size=100), 'poisson': np.random.poisson(size=100)}) df.describe() #输出基本统计量 df.plot() plt.show() df['sex'].value_counts() df['sex'].value_counts().plot(kind='barh')

    3.使用series绘制柱状图

    from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt fig,axes = plt.subplots(2,1) df = pd.Series(np.random.rand(16),index = list('abcdefgijkpolikj')) df.plot.bar(ax=axes[0],color='r',alpha=0.7) #生成垂直柱状图 df.plot.barh(ax=axes[1],color='r',alpha=0.7) #生成水平柱状图 plt.show()

    4.使用DataFrame绘制柱状图

    from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame(np.random.rand(4,4),index = ['one','two','three','four'],columns = pd.Index(['A','B','C','D'],name='bar')) df.plot.bar() plt.show()

    5.使用DataFrame的hist方法生成直方图

    import pandas as pd from pandas import Series,DataFrame import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'a':np.random.randn(1000),'b':np.random.randn(1000),},columns=['a','b']) df.plot.hist(bins=20) #若加入stacked=true,则可以绘制叠加的直方图 plt.show()

    七、pandas文件操作

    data=pd.read_csv('05_Regression_5.2_logreg_credit_scores.csv',sep=';') #读取csv文件 data=pd.read_table('iris.data',sep=',',header=None) data.head(6) #输出前6行数据 data.to_csv('iris.csv') #保存为csv文件

    八、pandas数据清洗与整理

    1.数据清洗

    df1 = DataFrame([[3,5,3],[1,6,np.nan], ['lili',np.nan,'pop'],[np.nan,'a','b']]) #生成四行三列的数组 df1.isnull() #对数组每个数组进行判定,出现True的为缺失值 df1.notnull() #False为缺失值 df1.isnull().sum() #输出每列缺失值的数量 df1.isnull().sum().sum() #输出数组缺失值的数量 df1.isnull().any() #判断那些列存在缺失值 df1.isnull().values.any() #判断是否每列都有缺失值。是返回True,反之返回False df1.info() #dataframe.info()函数用于获取 DataFrame 的简要摘要 df1.dropna() #删除所有带有缺失值的行/列,返回一个新的数组,不影响原数组 df2.ix[2,:] = np.nan #第3行的数据全部改为缺失值 df2[3] = np.nan #第3列的数据全部改为缺失值 df2.dropna(how='all') #删除所有带有缺失值的行 df2.dropna(how='all',axis=1) #删除所有带有缺失值的列 df2.fillna(0) #填充所有缺失值为0,返回新数组,不改变原数组 df2.fillna({0:1,1:6,2:9,3:11}) #将第1列的缺失值填充为1,第2列的缺失值填充为6,第3列的缺失值填充为9,第4列的缺失值填充为11 df2.fillna({1:6,3:0},inplace=True) #参数inplace意思为改动原数组,默认为False df2.fillna(method='ffill') #向下填充,返回新数组,不改变原数组 df2[0] = df2[0].fillna(df2[0].mean()) #第一列的平均值填充(计算平均数时不包括那个缺失的数据)

    2.重复数据

    duplicated,drop_duplicates函数讲解

    data = { 'name':['张三', '李四', '张三', '小明'], 'sex':['female', 'male', 'female', 'male'], 'year':[2001, 2002, 2001, 2002], 'city':['北京', '上海', '北京', '北京'] } df1 = DataFrame(data) df1.duplicated() #判断每一行是否有重复数据 df1.drop_duplicates(inplace=True) #删除重复值,改变原数组 df1.drop_duplicates(['sex','year']) #删除sex列和year列相同的数组数据 df1.drop_duplicates(['sex','year'],keep='last')#keep为保留最后一次出现的重复数据

    3.替换值

    data = { 'name':['张三', '李四', '王五', '小明'], 'sex':['female', 'male', '', 'male'], 'year':[2001, 2003, 2001, 2002], 'city':['北京', '上海', '', '北京'] } df1 = DataFrame(data) df1.replace(['',2001],['不详',2002]) #将空数据替换为不详,将2001替换为2001 df1.replace({'':'不详',2001:2002}) #作用与上同 def f(x): if x >= 90: return '优秀' elif 70<=x<90: return '良好' elif 60<=x<70: return '合格' else: return '不合格' df2['class'] = df2['math'].map(f) #map()将一个自定义函数应用于Series结构中的每个元素.对应此句代码,即是针对数组math列中的每个元素 del df2['class'] #删除者一列元素 df2['class'] = df2['math'].apply(f) #apply()将一个函数作用于DataFrame中的每个行或者列

    4.虚拟变量

    pandas的get_dummies函数讲解

    df = DataFrame({ '朝向':['东','南','东','西','北'], '价格':[1200,2100,2300,2900,1400] }) # 哑变量(0,1)转化One-Hot编码 pd.get_dummies(df['朝向']) #转换变量,有的数据显示1,没有的数据显示0

    5.数据合并和重塑

    merge函数讲解

    price = DataFrame({ 'fruit':['apple','banana','orange'], 'price':[23,32,45] }) amount = DataFrame({ 'fruit':['apple','banana','apple','apple','banana','pear'], 'amount':[5,3,6,3,5,7] }) pd.merge(amount,price,on='fruit') #合并这2个数组,

    concat函数讲解

    s1 = Series([0,1],index=['a','b']) s2 = Series([2,3],index=['c','d']) s3 = Series([4,5],index=['e','f']) pd.concat([s1,s2,s3]) #concat函数连接

    6.数据重塑

    stack和unstack函数讲解

    result = df.stack() result.unstack()

    八、综合案例——小费数据集

    import numpy as np from pandas import Series,DataFrame import pandas as pd import seaborn as sns #导入seaborn库 tips=sns.load_dataset('tips') tips.head() tips.shape tips.describe() tips.info() tips.plot(kind='scatter',x='total_bill',y='tip') male_tip = tips[tips['sex'] == 'Male']['tip'].mean() female_tip = tips[tips['sex'] == 'Female']['tip'].mean() s = Series([male_tip,female_tip],index=['male','female']) s.plot(kind='bar') tips['day'].unique() sun_tip = tips[tips['day'] == 'Sun']['tip'].mean() sat_tip = tips[tips['day'] == 'Sat']['tip'].mean() thur_tip = tips[tips['day'] == 'Thur']['tip'].mean() fri_tip = tips[tips['day'] == 'Fri']['tip'].mean() s = Series([thur_tip,fri_tip,sat_tip,sun_tip],index=['Thur','Fri','Sat','Sun']) s.plot(kind='bar') tips['percent_tip'] = tips['tip']/(tips['total_bill']+tips['tip']) tips.head(10) tips['percent_tip'].hist(bins=50)
    Processed: 0.010, SQL: 8