pandas打印DataFrame的前几行、后几行样本和随机抽样

本文介绍Pandas库中用于快速预览数据的head、tail和sample函数,这些函数可以帮助数据分析师快速理解数据集的结构和内容,适用于各种规模的数据集。

在使用pandas对结构化数据进行探索性分析时,我们经常需要打印几条样本出来看看数据读取和处理是否正确,除了用iloc函数以索引区间的方式读取,pandas为我们提供了更简单的head和tail函数,这两个函数的使用方法和效果如下。

1、head函数

pandas中的head函数的使用方法如下:

import numpy as np
import pandas as pd

df_data = pd.DataFrame(np.random.rand(10, 5))
# 打印全体数据
print(df_data)
# 打印前5条数据
print(df_data.head())
# 打印前2条数据
print(df_data.head(2))

结果如下:

          0         1         2         3         4
0  0.718092  0.899116  0.125582  0.978291  0.906551
1  0.173210  0.433652  0.620770  0.824463  0.037136
2  0.012881  0.683509  0.449453  0.859218  0.464844
3  0.243671  0.436372  0.518020  0.091002  0.631860
4  0.044998  0.688442  0.487132  0.230478  0.963189
5  0.453796  0.276635  0.458563  0.165412  0.763591
6  0.975923  0.890063  0.462410  0.168376  0.375301
7  0.694347  0.104572  0.511853  0.987440  0.852707
8  0.290416  0.476767  0.009371  0.360272  0.420603
9  0.813110  0.623151  0.358813  0.697292  0.004572
          0         1         2         3         4
0  0.718092  0.899116  0.125582  0.978291  0.906551
1  0.173210  0.433652  0.620770  0.824463  0.037136
2  0.012881  0.683509  0.449453  0.859218  0.464844
3  0.243671  0.436372  0.518020  0.091002  0.631860
4  0.044998  0.688442  0.487132  0.230478  0.963189
          0         1         2         3         4
0  0.718092  0.899116  0.125582  0.978291  0.906551
1  0.173210  0.433652  0.620770  0.824463  0.037136

我们进一步看一下pandas中head函数的源码可以发现它也是基于iloc函数实现的,且默认返回前5行数据:

    def head(self, n=5):
        """
        Return the first `n` rows.

        This function returns the first `n` rows for the object based
        on position. It is useful for quickly testing if your object
        has the right type of data in it.

        Parameters
        ----------
        n : int, default 5
            Number of rows to select.

        Returns
        -------
        obj_head : same type as caller
            The first `n` rows of the caller object.

        See Also
        --------
        DataFrame.tail: Returns the last `n` rows.

        Examples
        --------
        >>> df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion',
        ...                    'monkey', 'parrot', 'shark', 'whale', 'zebra']})
        >>> df
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey
        5     parrot
        6      shark
        7      whale
        8      zebra

        Viewing the first 5 lines

        >>> df.head()
              animal
        0  alligator
        1        bee
        2     falcon
        3       lion
        4     monkey

        Viewing the first `n` lines (three in this case)

        >>> df.head(3)
              animal
        0  alligator
        1        bee
        2     falcon
        """

        return self.iloc[:n]

2、tail函数

pandas中的tail函数的使用方法如下:

import numpy as np
import pandas as pd

df_data = pd.DataFrame(np.random.rand(10, 5))
# 打印全体数据
print(df_data)
# 打印后5条数据
print(df_data.tail())
# 打印后2条数据
print(df_data.tail(2))

结果如下:

          0         1         2         3         4
0  0.400922  0.146871  0.141041  0.839072  0.113124
1  0.885119  0.519281  0.571275  0.304061  0.965502
2  0.309809  0.061705  0.911406  0.954084  0.296767
3  0.965902  0.351461  0.398504  0.664548  0.764347
4  0.602855  0.582827  0.534116  0.226877  0.539045
5  0.736614  0.200998  0.170951  0.200885  0.623913
6  0.410535  0.347231  0.934425  0.130389  0.104412
7  0.871398  0.788983  0.210943  0.519613  0.133114
8  0.353736  0.986401  0.385541  0.691156  0.025777
9  0.978579  0.827868  0.074246  0.846744  0.063719
          0         1         2         3         4
5  0.736614  0.200998  0.170951  0.200885  0.623913
6  0.410535  0.347231  0.934425  0.130389  0.104412
7  0.871398  0.788983  0.210943  0.519613  0.133114
8  0.353736  0.986401  0.385541  0.691156  0.025777
9  0.978579  0.827868  0.074246  0.846744  0.063719
          0         1         2         3         4
8  0.353736  0.986401  0.385541  0.691156  0.025777
9  0.978579  0.827868  0.074246  0.846744  0.063719

看一下源码可以发现tail函数和head函数类似,也是基于iloc函数实现的,默认也是返回后5条数据。

3、sample函数

我们可以进一步使用pandas中的sample函数从数据框中抽取指定数量的样本,代码如下:

import numpy as np
import pandas as pd

df_data = pd.DataFrame(np.random.rand(10, 5))
# 打印全体数据
print(df_data)
# 打印随机抽取的3条数据
print(df_data.sample(n=3))

效果如下:

          0         1         2         3         4
0  0.939711  0.620093  0.246614  0.399083  0.683863
1  0.432783  0.514398  0.764729  0.734619  0.546725
2  0.602358  0.731698  0.329452  0.413731  0.483912
3  0.035878  0.473099  0.938656  0.438246  0.719304
4  0.639476  0.168669  0.886065  0.422071  0.108447
5  0.508343  0.838977  0.768282  0.155232  0.706890
6  0.963683  0.492637  0.890227  0.742109  0.058080
7  0.534936  0.163335  0.582532  0.519570  0.833517
8  0.574580  0.088736  0.331792  0.954629  0.896857
9  0.626263  0.933672  0.348024  0.383196  0.777881
          0         1         2         3         4
5  0.508343  0.838977  0.768282  0.155232  0.706890
7  0.534936  0.163335  0.582532  0.519570  0.833517
8  0.574580  0.088736  0.331792  0.954629  0.896857

 

<think>好的,我现在需要帮助用户了解如何查看DataFrame。首先,用户之的问题是关于处理气象数据,将npz文件转为DataFrame并计算中国东部的平均气温。现在他们想知道如何查看DataFrame,可能是在处理数据的过程中需要验证数据是否正确加载,或者检查结构是否符合预期。 用户可能处于数据处理的初步阶段,刚创建了DataFrame,需要确认数据是否正确。他们可能不太熟悉Pandas的基本操作,特别是如何快速查看数据的不同部分。需要考虑到他们可能的需求,比如查看几行、后几行、统计信息、列名、维度、数据类型等。此外,用户可能有处理大型数据集的情况,需要注意效率问题。 接下来,我应该分步骤解释不同的方法,从最简单的head()tail()开始,因为这些是最常用的方法,可以快速查看数据的结构。然后介绍shapecolumns属性,帮助用户了解数据的大小列名。describe()info()也是关键方法,能提供统计摘要数据类型信息。对于大型DataFrame样本查看特定值检查也很重要,比如sample()loc/iloc的使用。此外,用户可能需要了解如何检查缺失值,这在数据处理中很常见。最后,可视化方法可以帮助更直观地理解数据分布。 还要注意提醒用户处理大数据时的注意事项,比如避免使用head()全部显示,可能导致内存问题。另外,可能需要提到转置或调整显示选项,比如设置最大行数列数,这在处理宽表或长表时很有用。用户之的问题中提到经纬度作为行列标签,所以在示例中可能需要调整显示方式,比如显示行列的标签是否正确。 需要确保示例代码准确,使用中文注释,并且考虑到用户的实际应用场景。比如,他们处理的是地理数据,可能DataFrame的行是纬度,列是经度,所以在查看数据时,需要确认行列标签是否正确显示。此外,用户可能需要提取特定区域的数据,所以在查看DataFrame结构时,验证筛选条件是否正确应用也很重要。 最后,应该总结各种方法的适用场景,帮助用户根据不同的需求选择合适的方法。比如,快速预览用head/tail,统计信息用describe,结构信息用shapecolumns,处理大数据用sample或分块处理。这些信息能帮助用户高效地查看验证他们的DataFrame数据。</think>以下是查看DataFrame的常用方法及示例代码,按使用场景分类说明: --- ### **一、基础查看方法** #### 1. 查看首尾数据 ```python # 查看5行(默认) print(df.head()) # 查看3行 print(df.head(3)) # 查看后5行 print(df.tail()) # 查看后2行 print(df.tail(2)) ``` #### 2. 快速统计摘要 ```python # 数值型列的统计信息(均值、标准差、分位数等) print(df.describe()) # 包含非数值列的统计信息 print(df.describe(include='all')) ``` --- ### **二、结构信息查看** #### 1. 维度与列名 ```python # 查看行数列数 (返回元组:行数, 列数) print("数据维度:", df.shape) # 查看列名列表 print("列名:", df.columns.tolist()) # 查看索引(行标签) print("索引:", df.index) ``` #### 2. 数据类型与内存 ```python # 每列数据类型 + 非空值数量 print(df.info()) # 查看具体某列类型 print(df['温度'].dtype) # 查看内存占用 print(df.memory_usage(deep=True)) ``` --- ### **三、内容深度查看** #### 1. 按条件筛选查看 ```python # 查看经纬度在特定范围的记录 print(df[(df['经度'] >= 110) & (df['纬度'] <= 40)]) # 查看最大温度所在行 print(df[df['温度'] == df['温度'].max()]) ``` #### 2. 行列切片 ```python # 查看3行、2列(基于位置) print(df.iloc[:3, :2]) # 查看纬度20-30之间的行(基于标签) print(df.loc[20:30, ['经度', '温度']]) ``` --- ### **四、高级技巧** #### 1. 缺失值检查 ```python # 每列缺失值数量 print(df.isnull().sum()) # 可视化缺失值分布(需matplotlib) import matplotlib.pyplot as plt plt.figure(figsize=(10,3)) plt.title("缺失值热力图") plt.imshow(df.isnull(), aspect='auto') plt.show() ``` #### 2. 抽样查看大数据 ```python # 随机查看5行 print(df.sample(5)) # 按10%比例随机抽样 print(df.sample(frac=0.1)) ``` #### 3. 转置查看 ```python # 将行列互换(适合宽表变长表) print(df.T.head()) ``` --- ### **五、可视化辅助** ```python # 快速绘制100行折线图(适合时间序列) df['温度'].iloc[:100].plot(title="温度变化趋势") plt.show() # 绘制直方图查看分布 df['温度'].hist(bins=20) plt.xlabel("温度值") plt.ylabel("频次") plt.show() ``` --- ### **注意事项** 1. **大数据处理**:若DataFrame过大(如超过10万行),避免直接`print(df)`,优先用`df.head()`或抽样查看 2. **显示设置**:调整显示参数可完整查看内容 ```python # 设置最大显示行数 pd.set_option('display.max_rows', 500) # 禁止科学计数法显示 pd.set_option('display.float_format', '{:.2f}'.format) ``` 3. **地理数据特殊处理**:若您的DataFrame以经纬度为行列标签(如您之的案例),可用以下方式验证: ```python print("纬度范围:", df.index.min(), "~", df.index.max()) print("经度范围:", df.columns.min(), "~", df.columns.max()) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值