Concept Flow - head() and tail()
Start with DataFrame
Call head(n)
Select first n rows
Return subset DataFrame
The flow shows how calling head(n) or tail(n) on a DataFrame returns the first or last n rows respectively.
import pandas as pd df = pd.DataFrame({'A': range(1,6), 'B': list('abcde')}) print(df.head(3)) print(df.tail(2))
| Step | Action | Input DataFrame | Method Called | Parameter n | Output DataFrame |
|---|---|---|---|---|---|
| 1 | Create DataFrame | {'A':[1,2,3,4,5], 'B':['a','b','c','d','e']} | None | None | Full DataFrame with 5 rows |
| 2 | Call head(3) | Full DataFrame | head | 3 | First 3 rows: rows 0,1,2 |
| 3 | Call tail(2) | Full DataFrame | tail | 2 | Last 2 rows: rows 3,4 |
| 4 | End | N/A | N/A | N/A | Execution complete |
| Variable | Start | After head(3) | After tail(2) | Final |
|---|---|---|---|---|
| df | N/A | Full DataFrame with 5 rows | Full DataFrame with 5 rows | Full DataFrame with 5 rows |
| head_df | N/A | DataFrame with rows 0,1,2 | DataFrame with rows 0,1,2 | DataFrame with rows 0,1,2 |
| tail_df | N/A | N/A | DataFrame with rows 3,4 | DataFrame with rows 3,4 |
head(n) returns the first n rows of a DataFrame. tail(n) returns the last n rows. If n > number of rows, all rows are returned. Rows are zero-indexed. Useful for quick data preview.
head() function do when used on a DataFrame?head()head() function is designed to display the first few rows of a DataFrame to give a quick look at the data.tail() shows the last few rows, counting rows is done by len(), and deleting rows is not the function of head().head() = first rows [OK]df?tail() function returns the last rows of a DataFrame, and it accepts a number to specify how many rows.df.tail(3) is correct; head() shows first rows, and last() or end() are not valid pandas functions.df below:import pandas as pd
data = {'Name': ['Anna', 'Bob', 'Cara', 'Dan', 'Eva'], 'Age': [23, 35, 45, 29, 40]}
df = pd.DataFrame(data)df.head(2) return?head(2) doeshead(2) returns the first 2 rows of the DataFrame.import pandas as pd
data = {'A': [1, 2, 3, 4, 5]}
df = pd.DataFrame(data)
print(df.tail[3])df.tail[3] which uses square brackets. Methods require parentheses.df.tail(3) to call the method with argument 3.df with 1000 rows. You want to quickly check the first 5 and last 5 rows together. Which code snippet correctly shows this?pd.concat() or append() method.df.head() + df.tail() and df.head() & df.tail() are invalid operations for DataFrames. df.head().append(df.tail()) works but is deprecated in recent pandas versions. pd.concat([df.head(), df.tail()]) is the recommended way.Pass the test and this pattern moves unknown