pandas顯示前n行和最後n行
阿新 • • 發佈:2020-12-09
目錄
Exploring data frames
本文主要介紹pandas中的head和tail函式, 來查詢資料
- jupyter notebook 簡單使用
- pandas.head
- pandas.tail
Get help on Jupyter notebook
如果想要檢視類的屬性或者方法名, 可以使用help和?
- object_name?
- help(object_name)
建立dataframe
本文將以下面的DataFrame進行講解
import numpy as np import pandas as pd df = pd.DataFrame({'name': ['Tom', 'Sam', 'Steve', 'David', 'Simon', 'Angel'], 'ages': [18, 19, 20, 21, 22, 23]}) print(df) ''' name ages 0 Tom 18 1 Sam 19 2 Steve 20 3 David 21 4 Simon 22 5 Angel 23 '''
顯示前n行
df.head
先看下head的說明
In: df.head? Signature: df.head(n: int=5) -> ~FrameOrSeries Docstring: 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. For negative values of `n`, this function returns all rows except the last `n` rows, equivalent to ``df[:-n]``. Parameters ---------- n: int, default 5 Number of rows to select. Returns ------- 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 For negative values of `n` >> > df.head(-3) animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey 5 parrot
方法一: 顯示前3行
方法二: 顯示前3行
顯示後n行
先看下tail的說明
Signature: df.tail(n:int=5) -> ~FrameOrSeries
Docstring:
Return the last `n` rows.
This function returns last `n` rows from the object based on
position. It is useful for quickly verifying data, for example,
after sorting or appending rows.
For negative values of `n`, this function returns all rows except
the first `n` rows, equivalent to ``df[n:]``.
Parameters
----------
n : int, default 5
Number of rows to select.
Returns
-------
type of caller
The last `n` rows of the caller object.
See Also
--------
DataFrame.head : The first `n` rows of the caller object.
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 last 5 lines
>>> df.tail()
animal
4 monkey
5 parrot
6 shark
7 whale
8 zebra
Viewing the last `n` lines (three in this case)
>>> df.tail(3)
animal
6 shark
7 whale
8 zebra
For negative values of `n`
>>> df.tail(-3)
animal
3 lion
4 monkey
5 parrot
6 shark
7 whale
8 zebra
方法一: 顯示最後2行
方法二: 顯示最後2行
外傳
到這裡, 我們已經學會顯示前n行和最後n行.那我們如何知道檔案有多少行呢?
- 方案一: 用肉眼數(不推薦)
- 方案二: df.shape
- 方案三: len(df)
我是總結
- df.shape 獲取rows和cols
- df.head(n) 顯示前n行
- df.tail(n) 顯示最後n行
掃碼關注公眾號: 風起帆揚了
來一起學習,成長,分享
航行在測試的大道上
喜歡就點贊吧