Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Common Pandas functions

Common Pandas functions

The following lists some commonly used Pandas functions along with usage examples:

Read data

function Description
pd.read_csv(filename) Read a CSV file;
pd.read_excel(filename) Read an Excel file;
pd.read_sql(query, connection_object) Read data from a SQL database;
pd.read_json(json_string) Read data from a JSON string;
pd.read_html(url) Read data from an HTML page.

Example

import

pandas

as

pd

Read data from a CSV file

df

=

pd.

read_csv

(

'data.csv'

)

Read data from an Excel file

df

=

pd.

read_excel

(

'data.xlsx'

)

Read data from a SQL database

import

sqlite3

conn

=

sqlite3.

connect

(

'database.db'

)

df

=

pd.

read_sql

(

'SELECT * FROM table_name'

,

conn

)

Read data from a JSON string

json_string

=

'{"name": "John", "age": 30, "city": "New York"}'

df

=

pd.

read_json

(

json_string

)

Read data from an HTML page

url

=

'https://www.runoob.com'

dfs

=

pd.

read_html

(

url

)

df

=

dfs

[

0

]

Select the first DataFrame


View data

function Description
df.head(n) Display the first n rows;
df.tail(n) Display the last n rows;
df.info() Display data information, including column names, data types, missing values, etc.;
df.describe() Display basic statistics of the data, including mean, variance, maximum, minimum, etc.;
df.shape Display the number of rows and columns in the data.

Example

Display the first five rows

df.

head

(

)

Display the last five rows

df.

tail

(

)

Display data information

df.

info

(

)

Display basic statistics

df.

describe

(

)

Display the number of rows and columns

df.

shape

Example

import

pandas

as

pd

data

=

[

   

{

"name"

:

"Google"

,

"likes"

:

25

,

"url"

:

"https://www.google.com"

}

,

   

{

"name"

:

"Runoob"

,

"likes"

:

30

,

"url"

:

"https://www.runoob.com"

}

,

   

{

"name"

:

"Taobao"

,

"likes"

:

35

,

"url"

:

"https://www.taobao.com"

}

]

df

=

pd.

DataFrame

(

data

)

Display the first two rows

print

(

df.

head

(

2

)

)

Display the last row of data

print

(

df.

tail

(

1

)

)

The output of the above example is:



     name  likes                     url

0  Google     25  https://www.google.com

1  Runoob     30  https://www.runoob.com

     name  likes                     url

2  Taobao     35  https://www.taobao.com


Data cleaning

function Description
df.dropna() Drop rows or columns containing missing values;
df.fillna(value) Replace missing values with a specified value;
df.replace(old_value, new_value) Replace a specified value with a new value;
df.duplicated() Check for duplicate data;
df.drop_duplicates() Remove duplicate data.

Example

Remove rows or columns containing missing values

df.

dropna

(

)

Replace missing values with a specified value

df.

fillna

(

0

)

Replace a specified value with a new value

df.

replace

(

'old_value'

,

'new_value'

)

Check for duplicate data

df.

duplicated

(

)

Remove duplicate data

df.

drop_duplicates

(

)


Data Selection and Slicing

function Description
df[column_name] Select specified columns;
df.loc[row_index, column_name] Select data by label;
df.iloc[row_index, column_index] Select data by position;
df.ix[row_index, column_name] Select data by label or position;
df.filter(items=[column_name1, column_name2]) Select specified columns;
df.filter(regex='regex') Select columns whose names match a regular expression;
df.sample(n) Randomly select n rows.

Example

Select specified columns

df

[

'column_name'

]

Select data by label

df.

loc

[

row_index

,

column_name

]

Select data by position

df.

iloc

[

row_index

,

column_index

]

Select data by label or position

df.

ix

[

row_index

,

column_name

]

Select specified columns

df.

filter

(

items

=

[

'column_name1'

,

'column_name2'

]

)

Select columns whose names match a regular expression

df.

filter

(

regex

=

'regex'

)

Randomly select n rows

df.

sample

(

n

=

5

)


Data sorting

function Description
df.sort_values(column_name) Sort by the values of a specified column;
df.sort_values([column_name1, column_name2], ascending=[True, False]) Sort by the values of multiple columns;
df.sort_index() Sort by index.

Example

Sort by the values of a specified column

df.

sort_values

(

'column_name'

)

Sort by the values of multiple columns

df.

sort_values

(

[

'column_name1'

,

'column_name2'

]

,

ascending

=

[

True

,

False

]

)

Sort by index

df.

sort_index

(

)


Data Grouping and Aggregation

function Description
df.groupby(column_name) Group by a specified column;
df.aggregate(function_name) Perform aggregation on the grouped data;
df.pivot_table(values, index, columns, aggfunc) Generate a pivot table.

Example

Group by a specified column

df.

groupby

(

'column_name'

)

Perform aggregation on the grouped data

df.

aggregate

(

'function_name'

)

Generate a pivot table

df.

pivot_table

(

values

=

'value'

,

index

=

'index_column'

,

columns

=

'column_name'

,

aggfunc

=

'function_name'

)


Data Merging

function Description
pd.concat([df1, df2]) Merge multiple DataFrames by rows or columns;
pd.merge(df1, df2, on=column_name) Merge two DataFrames by a specified column.

Example

Merge multiple DataFrames by rows or columns

df

=

pd.

concat

(

[

df1

,

df2

]

)

Merge two DataFrames by a specified column

df

=

pd.

merge

(

df1

,

df2

,

on

=

'column_name'

)


Data Selection and Filtering

function Description
df.loc[row_indexer, column_indexer] Select rows and columns by label.
df.iloc[row_indexer, column_indexer] Select rows and columns by position.
df[df['column_name'] > value] Select rows in a column that satisfy a condition.
df.query('column_name > value') Use a string expression to select rows in a column that satisfy a condition.

Data Statistics and Description

function Description
df.describe() Compute basic statistics such as mean, standard deviation, minimum, maximum, etc.
df.mean() Compute the mean of each column.
df.median() Compute the median of each column.
df.mode() Compute the mode of each column.
df.count() Count the non-missing values in each column.

Example

Suppose we have the following JSON data, saved to the data.json file:

data.json file

[

 

{

   

"name"

:

"Alice"

,

   

"age"

:

25

,

   

"gender"

:

"female"

,

   

"score"

:

80

 

}

,

 

{

   

"name"

:

"Bob"

,

   

"age"

:

null

,

   

"gender"

:

"male"

,

   

"score"

:

90

 

}

,

 

{

   

"name"

:

"Charlie"

,

   

"age"

:

30

,

   

"gender"

:

"male"

,

   

"score"

:

null

 

}

,

 

{

   

"name"

:

"David"

,

   

"age"

:

35

,

   

"gender"

:

"male"

,

   

"score"

:

70

 

}

]

We can use Pandas to read JSON data and perform operations such as data cleaning and processing, data selection and filtering, and data statistics and description, as follows:

Example

import

pandas

as

pd

Read JSON Data

df

=

pd.

read_json

(

'data.json'

)

Delete missing values

df

=

df.

dropna

(

)

Fill missing values with a specified value

df

=

df.

fillna

(

{

'age'

:

0

,

'score'

:

0

}

)

Rename column names

df

=

df.

rename

(

columns

=

{

'name'

:

'Name'

,

'age'

:

'Age'

,

'gender'

:

'Gender'

,

'score'

:

'Score'

}

)

Sort by score

df

=

df.

sort_values

(

by

=

'Score'

,

ascending

=

False

)

Group by gender and compute the average age and score

grouped

=

df.

groupby

(

'Gender'

)

.

agg

(

{

'Age'

:

'mean'

,

'Score'

:

'mean'

}

)

Select rows with scores greater than or equal to 90, keeping only the name and score columns

df

=

df.

loc

[

df

[

'Score'

]

=

90

,

[

'Name'

,

'Score'

]

]

Compute basic statistics for each column

stats

=

df.

describe

(

)

Compute the mean of each column

mean

=

df.

mean

(

)

Compute the median of each column

median

=

df.

median

(

)

Compute the mode of each column

mode

=

df.

mode

(

)

Count the non-missing values in each column

count

=

df.

count

(

)

The output is as follows:

# df

   姓名  年龄 性别  成绩

1  Bob   0  male  90



# grouped

             年龄  成绩

性别                

female  25.000000  80

male    27.500000  80



# stats

         成绩

count   1.0

mean   90.0

std     NaN

min    90.0

25%    90.0

50%    90.0

75%    90.0

max    90.0



# mean

成绩    90.0

dtype: float64



# median

成绩    90.0

dtype: float64



# mode

    姓名    成绩

0  Bob  90.0



# count

姓名    1

成绩    1

dtype: int64