Pandas(三):DataFrame

    科技2025-09-05  28

    点击跳转 《Pandas系列目录》


    文章目录

    1. 创建DataFrame2. DataFrame基本操作3. 分析DataFrame数据


    1. 创建DataFrame

    pandas.DataFrame(data=None, index=None, columns=None) data ndarray、list或dict index 行索引 columns 列名列表 import pandas as pd d = [[1.3, 2.0, 3, 4], [2, 4, 1, 4], [2, 5, 1.9, 7], [3, 1, 0, 11]] df = pd.DataFrame(d, index=['a', 'b', 'c', 'd'], columns=list('ABCD')) print(df) # 生成缺失值矩阵 df1 = pd.DataFrame(index=['1', '2'], columns=['b', 'c']) print(df1) # 生成全零矩阵 df2 = pd.DataFrame(0, index=['1', '2'], columns=['b', 'c']) print(df2) d = {'color': ['blue', 'green', 'yellow', 'red', 'white'], 'object': ['ball', 'pen', 'pencil', 'paper', 'mug'], 'price': [1.2, 1.0, 0.6, 0.9, 1.7]} df3 = pd.DataFrame(d, index=['a', 'b', 'c', 'd', 'e']) print(df3) 基本属性

    # 查看DataFrame的常用属性 import pandas as pd detail = pd.read_excel('...') print('订单详情表的索引为:', detail.index) print('订单详情表的所有值为:\n', detail.values) print('订单详情表的列名为:\n', detail.columns) print('订单详情表的数据类型为:\n', detail.dtypes) # 查看元素个数 print('订单详情表的元素个数为:', detail.size) print('订单详情表的维度数为:', detail.ndim) print('订单详情表的形状为:', detail.shape) # 使用T属性进行转置 print('订单详情表转置前形状为:', detail.shape) print('订单详情表转置后形状为为:', detail.T.shape)

    2. DataFrame基本操作

    查询

    打印所有列名

    DataFrame.columns

    下单最多的商品

    DataFrame.groupby('item_name').agg({'quatity':np.sum}).idxmax()

    对单列数据的访问:DataFrame的单列数据为一个Series。有以下两种方式

    以字典访问某一个key的值的方式,使用对应的列名

    order_id = detail['order_id']

    以属性的方式访问(不建议使用,易引起混淆)

    dishes_name = detail.dishes_name

    对某一列的某几行访问

    单独一列的DataFrame可以视为一个Series dishes_name = detail['dishes_name'][:5]

    对多列数据访问

    可以将多个列索引名称视为一个列表。同时访问DataFrame多列数据中的多行数据和访问单列数据的多行数据方法基本相同 orderDish = detail[['order_id', 'dishes_name']][:5]

    对某几行访问

    如果只是需要访问某几行数据,实现方式和上述的访问多列多行相似,选择所有列,使用“:”代替即可

    head和tail可以得到多行数据,但是用这两种方法得到的数据都是从开始或末尾获取的连续数据。默认参数为访问5行

    print('订单详情表中前十行数据为:\n', detail.head(10)) print('订单详情表中后五行数据为:\n', detail.tail())

    loc和iloc方法

    loc方法 针对DataFrame索引名称的切片方法,如果传入的不是索引名称,那么切片操作将无法执行。利用loc方法,能够实现所有单层索引切片操作DataFrame.loc[行索引名称或条件, 列索引名称] iloc方法 iloc和loc区别:iloc接收的必须是行索引和列索引的位置 DataFrame.iloc[行索引位置, 列索引位置] # 使用loc和iloc实现单列切片 dishes_name1 = detail.loc[:, 'dishes_name'] dishes_name2 = detail.iloc[:, 3] 使用loc方法和iloc方法实现多列切片,其原理的通俗解释就是将多列的列名或者位置作为一个列表或者数据传入 # 使用loc、iloc实现多列切片 orderDish1 = detail.loc[:, ['order_id', 'dishes_name']] orderDish2 = detail.iloc[:, [1, 3]] # 使用loc、iloc实现花式切片 print(detail.loc[3, ['order_id', 'dishes_name']]) print(detail.loc[2:6, ['order_id', 'dishes_name']]) print(detail.iloc[3, [1, 3]]) print(detail.iloc[2:7, [1, 3]]) 在loc使用的时候,内部传入的行索引名称如果为一个区间,则前后均为闭区间在iloc使用的时候,内部传入的行索引位置或列索引位置为区间时,则为前闭后开区间loc内部还可以传入表达式,结果会返回满足表达式的所有值 # 使用loc实现条件切片 print(detail.loc[detail['order_id'] == 458, ['order_id', 'dishes_name']]) # 使用iloc实现条件切片 print(detail.iloc[detail['order_id'] == 458, [1, 5]]) # 出错,iloc不接受Series print(detail.iloc[(detail['order_id'] == 458).values, [1, 5]]) # 正确 # 多条件索引 gmv2 = df.loc[(df['交易额'] >= 300) & (df['交易额'] <= 800), :]

    loc更加灵活多变,代码的可读性更高,iloc的代码简洁,但可读性不高。大多数时候建议使用loc方法

    ix方法

    ix方法像是loc和iloc的融合ix方法在使用时既可以接受索引名称,也可以接受索引位置。 DataFrame.ix[行索引名称或位置或条件, 列索引名称或位置] print(detail.ix[2:6, 5]) # 优先识别为名称 当索引名称和位置存在部分重叠时,ix默认优先识别名称使用ix参数时,尽量保持行索引名称和行索引位置重叠。一律为闭区间使用列索引名称,而非列索引位置,以提高代码可读性使用列索引位置时,需要注解,以提高代码可读性缺点:面对数据量巨大的任务时,效率低于loc和iloc方法。建议使用loc和iloc方法

    以某字开头的数据

    # 以字母G开头的球队数据 Gteam = [] for i in range(euro12['Team'].size): if euro12['Team'][i][0] == 'G': Gteam.append(i)

    修改

    更改DataFrame中的数据,原理是将这部分数据提取出来,重新赋值为新的数据注意:数据更改直接针对DataFrame原数据更改,操作无法撤销。如果做出更改,需要对更改条件做确认或对数据进行备份 # 更改指定数据 detail.loc[detail['order_id'] == 458, 'order_id'] = 45800

    将str类型(货币类型)转换为浮点数类型

    chipo['item_price'] = chipo['item_price'].str[1:].astype("float64")

    排序

    先按Red Cards排序,再按Yellow Cards排序ascending = True:升序 discipline = discipline.sort_values(ascending=True, by=['Red Cards', 'Yellow Cards'])

    增添

    添加一列的方法非常简单,只需要新建一个列索引,并对该索引下的数据进行赋值即可

    # 创建新列 detail['payment'] = detail['counts'] * detail['amounts']

    若新增的一列值相同,则直接赋值一个常量即可

    # 创建新列,并全部赋值为cash detail['pay_way'] = 'cash'

    删除

    删除某列或某行数据时需要用到pandas提供的drop方法

    DataFrame.drop(labels, axis=0, level=None, inplace=False, errors='raise') axis=0:删除行axis=1:删除列

    常用参数

    detail.drop(labels='pay_way', axis=1, inplace=True) # 删除一列 detail.drop(labels=range(1, 11), axis=0, inplace=True) # 删除一行,行索引

    3. 分析DataFrame数据

    数值型特征的描述性统计:计算数值型数据的完整情况、最小值、均值、中位数、最大值、四分位数、极差、标准差、方差、协方差和变异系数等pandas库基于numpy,自然也可以用这些函数对数据框进行描述性统计

    print(np.mean(detail["amounts"]))

    pandas还提供了更加便利的方法来计算均值

    print(detail["amounts"].mean())

    还提供了一个方法叫做describe,能够一次性得出数据框所有数值型特征的非空值数目、均值、四分位数、标准差

    print(detail[["amounts", 'counts']].describe())

    获取describe()中的单个内容

    print(detail[["amounts", 'counts']].describe()['top'])

    类别型特征的描述性统计

    描述类别型特征的分布状况,可以使用频数统计表

    实现频数统计的方法:value_counts

    print(detail['dishes_name'].value_count()[0:10]) # 出现次数最多的前十名

    pandas提供了categories类,可以使用astype方法将目标特征的数据类型转换为category类别

    describe方法除了支持传统数值型以外,还能够支持对category类型的数据进行描述性统计

    四个统计量为:列非空元素的数目、类别的数目、数目最多的类别、数目最多的类别的数目 detail['dishes_name'] = detail["dishes_name"].astype('category') print(detail['dishes_name'].describe())
    Processed: 0.009, SQL: 8