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

Advanced Pandas Features

Advanced Pandas Features

Pandas provides very powerful data manipulation capabilities, suitable for complex tasks such as data cleaning, analysis, aggregation, and time series processing. Mastering Pandas' advanced features can greatly improve the efficiency of data processing and analysis.


I. Data merging and joining

Pandas provides several methods to merge and join different DataFrames, such as merge()、concat() and join(). These methods are commonly used to handle multiple data sets and complex merge tasks.

1. merge() - Database-style joining

merge() method allows two DataFrames to be merged based on certain columns, similar to the JOIN operation in SQL. It supports inner, outer, left, and right joins.

Parameters Description
left The left DataFrame
right The right DataFrame
how The merge method, supporting 'inner', 'outer', 'left', 'right'
on the column name to join on (if the two sides have different column names, you can use left_on and right_on)
left_on the join column of the left DataFrame
right_on the join column of the right DataFrame
suffixes add a suffix to distinguish duplicate column names

Example

import

pandas

as

pd

Sample data

left

=

pd.

DataFrame

(

{

'ID'

:

[

1

,

2

,

3

]

,

'Name'

:

[

'Alice'

,

'Bob'

,

'Charlie'

]

}

)

right

=

pd.

DataFrame

(

{

'ID'

:

[

1

,

2

,

4

]

,

'Age'

:

[

24

,

27

,

22

]

}

)

Inner join using merge

result

=

pd.

merge

(

left

,

right

,

on

=

'ID'

,

how

=

'inner'

)

print

(

result

)

Output:



   ID     Name  Age

0   1    Alice   24

1   2      Bob   27

2. concat() - Joining along an axis

concat() Used to concatenate multiple DataFrames along a specified axis (rows or columns), commonly for row-wise merging (vertical concatenation) or column-wise merging (horizontal concatenation).

Parameters Description
objs A list of DataFrames to be merged
axis the axis to merge along,0 indicates row-wise merging,1 indicates column-wise merging
ignore_index whether to ignore the index and regenerate it (default is False)
keys provide hierarchical indexes for the objects being merged

Example

import

pandas

as

pd

Sample data

df1

=

pd.

DataFrame

(

{

'A'

:

[

1

,

2

,

3

]

}

)

df2

=

pd.

DataFrame

(

{

'A'

:

[

4

,

5

,

6

]

}

)

Row-wise merge

result

=

pd.

concat

(

[

df1

,

df2

]

,

axis

=

0

,

ignore_index

=

True

)

print

(

result

)

Output:



   A

0  1

1  2

2  3

3  4

4  5

5  6

3. join() - Index-based joining

join() The method is a simplified joining operation in Pandas, usually used to join multiple DataFrames based on their indexes.

Parameters Description
other the other DataFrame to join with
how The merge method, supporting 'left', 'right', 'outer', 'inner'
on the column to join on; by default, based on the index

Example

import

pandas

as

pd

Sample data

left

=

pd.

DataFrame

(

{

'A'

:

[

1

,

2

,

3

]

}

,

index

=

[

1

,

2

,

3

]

)

right

=

pd.

DataFrame

(

{

'B'

:

[

4

,

5

,

6

]

}

,

index

=

[

1

,

2

,

4

]

)

Joining using join

result

=

left.

join

(

right

,

how

=

'inner'

)

print

(

result

)

Output:

   A  B

1  1  4

2  2  5


II. Pivot tables and cross tables

Pandas provides the pivot_table() method to create a pivot table, and the crosstab() method to compute a cross table. Both pivot tables and cross tables are ideal for summarizing and rearranging data.

1. pivot_table() - Creating a pivot table

Parameters Description
data The input data
values The columns to summarize
index Column used as the row index
columns Column used as the column index
aggfunc Aggregation function, defaults to mean, can be sum, count etc.
fill_value Fill missing values

Example

import

pandas

as

pd

Sample data

data

=

{

'Date'

:

[

'2024-01-01'

,

'2024-01-02'

,

'2024-01-03'

,

'2024-01-04'

]

,

       

'Category'

:

[

'A'

,

'B'

,

'A'

,

'B'

]

,

       

'Sales'

:

[

100

,

150

,

200

,

250

]

}

df

=

pd.

DataFrame

(

data

)

Create a pivot table

pivot_table

=

pd.

pivot_table

(

df

,

values

=

'Sales'

,

index

=

'Date'

,

columns

=

'Category'

,

aggfunc

=

'sum'

,

fill_value

=

0

)

print

(

pivot_table

)

Output:

Category         A    B

Date                    

2024-01-01     100    0

2024-01-02       0  150

2024-01-03     200    0

2024-01-04       0  250

2. crosstab() - Create a cross-tabulation

Parameters Description
index Row labels
columns Column labels
values Data used for computation (optional)
aggfunc Aggregation function, default count

Example

import

pandas

as

pd

Sample data

data

=

{

'Category'

:

[

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

]

,

       

'Region'

:

[

'North'

,

'South'

,

'North'

,

'South'

,

'West'

,

'East'

]

}

df

=

pd.

DataFrame

(

data

)

Create a cross-tabulation

cross_table

=

pd.

crosstab

(

df

[

'Category'

]

,

df

[

'Region'

]

)

print

(

cross_table

)

Output:

Region    East  North  South  West

Category                         

A           0      2      0     1

B           1      0      1     0


3. Applying custom functions

Pandas provides several methods for applying custom functions, used for data cleaning and transformation.

1. apply() - Apply a function to a DataFrame or Series

apply() The method allows applying custom functions on a DataFrame or Series, supporting operations on rows or columns.

Parameters Description
func The function to apply
axis Defaults to 0, meaning apply by column;1 means apply by row
raw Whether to pass the original data (defaults to False)
result_type Define the type of the output, such as expand, reduce, broadcast

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

'A'

:

[

1

,

2

,

3

,

4

]

,

'B'

:

[

10

,

20

,

30

,

40

]

}

)

Define a custom function

def

custom_func

(

x

)

:

   

return

x *

2

Apply a function to columns

df

[

'A'

]

=

df

[

'A'

]

.

apply

(

custom_func

)

print

(

df

)

Output:



   A   B

0  2  10

1  4  20

2  6  30

3  8  40

2. applymap() - Apply a function to an entire DataFrame

applymap() Can only be applied to a DataFrame, acting on every element in the DataFrame.

Parameters Description
func The function to apply

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

'A'

:

[

1

,

2

,

3

]

,

'B'

:

[

4

,

5

,

6

]

}

)

Apply a custom function to a DataFrame

df

=

df.

applymap

(

lambda

x: x **

2

)

print

(

df

)

Output:



   A  B

0  1  16

1  4  25

2  9  36

3. map() - Apply a function to a Series

map() Can apply a function or a mapping to each element of a Series.

Parameters Description
arg The function, dictionary, or Series to apply

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

'A'

:

[

'cat'

,

'dog'

,

'rabbit'

]

}

)

Map using a dictionary

df

[

'A'

]

=

df

[

'A'

]

.

map

(

{

'cat'

:

'kitten'

,

'dog'

:

'puppy'

}

)

print

(

df

)

Output:



       A

0  kitten

1   puppy

2     NaN


4. Grouping operations and aggregation

In Pandas, the groupby() method is very powerful and can be used for grouped aggregation, data transformation, and data filtering. Through groupby(), data can be grouped according to certain conditions for aggregation operations such as sum, mean, count, etc.

1. groupby() - Group data

Parameters Description
by The column or index to group by
axis The axis to group by, defaults to 0, meaning group by rows
level Group by the level of the index (for MultiIndex)

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

   

'Category'

:

[

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

]

,

   

'Value'

:

[

10

,

20

,

30

,

40

,

50

,

60

]

}

)

Group by the Category column and compute the sum of each group

grouped

=

df.

groupby

(

'Category'

)

[

'Value'

]

.

sum

(

)

print

(

grouped

)

Output:



Category

A    90

B    120

Name: Value, dtype: int64

2. Aggregation operations (agg())

agg() Used to perform complex aggregation operations; you can pass multiple functions to compute several aggregate values at once.

Parameters Description
func Aggregation function, can be a string or a custom function

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

   

'Category'

:

[

'A'

,

'B'

,

'A'

,

'B'

,

'A'

,

'B'

]

,

   

'Value'

:

[

10

,

20

,

30

,

40

,

50

,

60

]

}

)

Use agg() for multiple aggregation operations

grouped

=

df.

groupby

(

'Category'

)

[

'Value'

]

.

agg

(

[

sum

,

min

,

max

]

)

print

(

grouped

)

Output:

          sum  min  max

Category                

A          90   10   50

B         120   20   60


5. Time series processing

Pandas provides powerful time series processing features, including date parsing, frequency conversion, date range generation, time window operations, etc.

1. date_range() - Generate a time series

Parameters Description
start Start date
end End date
periods Number of time points to generate
freq Frequency (such as D for day,H for hour, etc.)

Example

import

pandas

as

pd

Generate a time series

date_range

=

pd.

date_range

(

start

=

'2024-01-01'

,

periods

=

5

,

freq

=

'D'

)

print

(

date_range

)

Output:

DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05'], dtype='datetime64[ns]', freq='D')

2. Date and time offsets

Use pd.Timedelta() Can perform time addition and subtraction.

Example

import

pandas

as

pd

Date offsets

date

=

pd.

to_datetime

(

'2024-01-01'

)

new_date

=

date + pd.

Timedelta

(

days

=

10

)

print

(

new_date

)

Output:



2024-01-11 00:00:00

3. Time window operations (Rolling, Expanding)

Use rolling() and expanding() The method performs rolling and expanding window operations, commonly used for moving averages in time series and similar calculations.

Method Description
rolling() Compute rolling window operations, commonly used for moving averages
expanding() Compute expanding window operations, cumulative values

Example

import

pandas

as

pd

Sample data

df

=

pd.

DataFrame

(

{

'Value'

:

[

10

,

20

,

30

,

40

,

50

]

}

)

Compute a 3-day rolling average

df

[

'Rolling_Mean'

]

=

df

[

'Value'

]

.

rolling

(

window

=

3

)

.

mean

(

)

print

(

df

)

Output:



   Value  Rolling_Mean

0     10            NaN

1     20            NaN

2     30     20.000000

3     40     30.000000

4     50     40.000000


6. Handling missing values

Pandas provides several methods to handle missing values (such as NaN). Common operations include filling missing values, removing missing values, etc.

Method Description
isna() Check for missing values, return a boolean
fillna() Fill missing values
dropna() Remove rows or columns containing missing values

Example

import

pandas

as

pd

import

numpy

as

np

Sample data

df

=

pd.

DataFrame

(

{

   

'A'

:

[

1

,

2

,

np.

nan

,

4

]

,

   

'B'

:

[

5

,

np.

nan

,

7

,

8

]

}

)

Fill missing values

df_filled

=

df.

fillna

(

0

)

print

(

df_filled

)

Output:

   A  B

0  1  5

1  2  0

2  0  7

3  4  8


7. MultiIndex

Pandas provides MultiIndex functionality, making it possible to handle complex data structures in a DataFrame or Series, especially for hierarchical data. With MultiIndex, we can group, select, slice, and aggregate data.

1. Creating a MultiIndex

can be used via pd.MultiIndex.from_tuples()、pd.MultiIndex.from_product() or set_index() method to create a MultiIndex.

Method 1: pd.MultiIndex.from_tuples()

Use tuples to create a MultiIndex, where each tuple corresponds to one index level.

Parameters Description
tuples Each tuple corresponds to one index value
names The name of each index level (optional)

Example

import

pandas

as

pd

Create tuples

index_tuples

=

[

(

'A'

,

1

)

,

(

'A'

,

2

)

,

(

'B'

,

1

)

,

(

'B'

,

2

)

]

Create a MultiIndex

multi_index

=

pd.

MultiIndex

.

from_tuples

(

index_tuples

,

names

=

[

'Letter'

,

'Number'

]

)

Create DataFrame

df

=

pd.

DataFrame

(

{

'Value'

:

[

10

,

20

,

30

,

40

]

}

,

index

=

multi_index

)

print

(

df

)

Output:

               Value

Letter Number       

A      1          10

       2          20

B      1          30

       2          40

Method 2: pd.MultiIndex.from_product()

Use the Cartesian product of multiple lists to create a MultiIndex, suitable for cases with many data dimensions.

Parameters Description
iterables Multiple lists or arrays
names The name of each index level (optional)

Example

import

pandas

as

pd

Create multiple lists

index_values

=

[

[

'A'

,

'B'

]

,

[

1

,

2

]

]

Create a MultiIndex

multi_index

=

pd.

MultiIndex

.

from_product

(

index_values

,

names

=

[

'Letter'

,

'Number'

]

)

Create DataFrame

df

=

pd.

DataFrame

(

{

'Value'

:

[

10

,

20

,

30

,

40

]

}

,

index

=

multi_index

)

print

(

df

)

Output:

               Value

Letter Number       

A      1          10

       2          20

B      1          30

       2          40

Method 3: use set_index() Create a MultiIndex

set_index() The method can convert DataFrame columns into a MultiIndex, suitable for creating a MultiIndex from existing data.

Parameters Description
keys Column names to use as the index (can be one or multiple columns)

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Letter'

:

[

'A'

,

'A'

,

'B'

,

'B'

]

,

   

'Number'

:

[

1

,

2

,

1

,

2

]

,

   

'Value'

:

[

10

,

20

,

30

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Set the MultiIndex

df.

set_index

(

[

'Letter'

,

'Number'

]

,

inplace

=

True

)

print

(

df

)

Output:

               Value

Letter Number       

A      1          10

       2          20

B      1          30

       2          40


2. MultiIndex operations

1. Accessing MultiIndex data

Data can be accessed through hierarchical indexes. Through loc[] or xs()(cross-section) data can be conveniently selected.

Use loc[] Select data:

Example

import

pandas

as

pd

Sample data

data

=

{

   

'Letter'

:

[

'A'

,

'A'

,

'B'

,

'B'

]

,

   

'Number'

:

[

1

,

2

,

1

,

2

]

,

   

'Value'

:

[

10

,

20

,

30

,

40

]

}

df

=

pd.

DataFrame

(

data

)

Set the MultiIndex

df.

set_index

(

[

'Letter'

,

'Number'

]

,

inplace

=

True

)

Select category 'A', all data where 'Number' is 1

print

(

df.

loc

[

'A'

,

1

]

)

Output:

Value    10

Name: (A, 1), dtype: int64

Use xs() Get cross-sectional data:

xs() The method can select slices of specified levels in a MultiIndex.

Example

Use xs to get all data where 'Number' is 1

print

(

df.

xs

(

1

,

level

=

'Number'

)

)

Output:



        Value

Letter       

A          10

B          30

2. Slicing a MultiIndex

Pandas supports slicing on MultiIndex, allowing different subsets to be selected by index level.

Example

Select all data where Letter is 'A'

print

(

df.

loc

[

'A'

]

)

Output:

        Value

Number       

1          10

2          20

3. Sorting a MultiIndex

Pandas' sort_index() method supports sorting a MultiIndex.

Example

Sort by MultiIndex

df_sorted

=

df.

sort_index

(

level

=

[

'Letter'

,

'Number'

]

,

ascending

=

[

True

,

False

]

)

print

(

df_sorted

)

Output:



               Value

Letter Number       

A      2          20

       1          10

B      2          40

       1          30

4. Aggregation operations

MultiIndex combined with groupby() can perform powerful aggregation operations, suitable for statistical analysis of complex data.

Example

Use groupby to aggregate a MultiIndex

df_grouped

=

df.

groupby

(

[

'Letter'

,

'Number'

]

)

.

sum

(

)

print

(

df_grouped

)

Output:

               Value

Letter Number       

A      1          10

       2          20

B      1          30

       2          40

5. Resetting the index

You can use the reset_index() method resets the MultiIndex to ordinary columns.

Example

Reset the index

df_reset

=

df.

reset_index

(

)

print

(

df_reset

)

Output:

  Letter  Number  Value

0      A       1     10

1      A       2     20

2      B       1     30

3      B       2     40

6. Missing values in a MultiIndex

Missing values in a MultiIndex can be handled through fillna() or dropna() , similar to a regular index.

Example

Introduce missing values into the sample data

data

=

{

   

'Letter'

:

[

'A'

,

'A'

,

'B'

,

'B'

]

,

   

'Number'

:

[

1

,

2

,

1

,

2

]

,

   

'Value'

:

[

10

,

None

,

30

,

40

]

}

df

=

pd.

DataFrame

(

data

)

df.

set_index

(

[

'Letter'

,

'Number'

]

,

inplace

=

True

)

Fill missing values

df_filled

=

df.

fillna

(

0

)

print

(

df_filled

)

Output:

               Value

Letter Number       

A      1          10

       2           0

B      1          30

       2          40