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

Pandas User Behavior Analysis in Action

Pandas User Behavior Analysis in Action

User behavior analysis is an important basis for product optimization. This case shows how to analyze user behavior data such as visits, retention, and conversion.


Data preparation

Simulate user behavior data

Example

import

pandas

as

pd

import

numpy

as

np

np.

random

.

seed

(

42

)

n_users

=

500

n_events

=

5000

Basic user information

users

=

pd.

DataFrame

(

{

   

"User ID"

:

range

(

1

,

n_users +

1

)

,

   

"Registration date"

: pd.

date_range

(

"2024-01-01"

,

periods

=

n_users

,

freq

=

"D"

)

[

:n_users

]

,

   

"Channel"

: np.

random

.

choice

(

[

"Organic search"

,

"Advertising"

,

"Referral"

,

"Social"

]

,

n_users

)

,

   

"Device"

: np.

random

.

choice

(

[

"PC"

,

"Mobile"

,

"Tablet"

]

,

n_users

,

p

=

[

0.3

,

0.6

,

0.1

]

)

}

)

User behavior events

events

=

pd.

DataFrame

(

{

   

"Event ID"

:

range

(

1

,

n_events +

1

)

,

   

"User ID"

: np.

random

.

randint

(

1

,

n_users +

1

,

n_events

)

,

   

"Event type"

: np.

random

.

choice

(

       

[

"Browse"

,

"Click"

,

"Favorite"

,

"Add to cart"

,

"Place order"

,

"Comment"

]

,

        n_events

,

        p

=

[

0.4

,

0.25

,

0.1

,

0.1

,

0.1

,

0.05

]

   

)

,

   

"Event time"

: pd.

date_range

(

"2024-01-15"

,

periods

=

n_events

,

freq

=

"10min"

)

}

)

Merge data

events

=

events.

merge

(

users

[

[

"User ID"

,

"Channel"

,

"Device"

]

]

,

on

=

"User ID"

)

print

(

"User data:"

)

print

(

users.

head

(

)

)

print

(

f

"\nNumber of users: {len(users)}"

)

print

(

"\nEvent data:"

)

print

(

events.

head

(

)

)

print

(

f

"\nNumber of events: {len(events)}"

)


User activity analysis

Event type distribution

Example

Event type statistics

event_dist

=

events

[

"Event type"

]

.

value_counts

(

)

event_pct

=

events

[

"Event type"

]

.

value_counts

(

normalize

=

True

)

100

print

(

"=== Event type distribution ===\n"

)

event_analysis

=

pd.

DataFrame

(

{

   

"Count"

: event_dist

,

   

"Proportion"

: event_pct.

round

(

2

)

}

)

print

(

event_analysis

)

print

(

)

Number of users per event type

event_users

=

events.

groupby

(

"Event type"

)

[

"User ID"

]

.

nunique

(

)

print

(

"Number of participating users per event type:"

)

print

(

event_users

)

User engagement

Example

User event statistics

user_events

=

events.

groupby

(

"User ID"

)

.

agg

(

{

   

"Event ID"

:

"count"

,

   

"Event type"

:

lambda

x: x.

nunique

(

)

}

)

.

rename

(

columns

=

{

   

"Event ID"

:

"Total events"

,

   

"Event type"

:

"Number of event types"

}

)

print

(

"=== User engagement ===\n"

)

print

(

f

"Average events per user: {user_events['Total events'].mean():.1f}"

)

print

(

f

"Median: {user_events['Total events'].median():.0f}"

)

print

(

f

"Maximum: {user_events['Total events'].max()}"

)

print

(

)

User segmentation

user_events

[

"Activity level"

]

=

pd.

cut

(

    user_events

[

"Total events"

]

,

    bins

=

[

0

,

3

,

10

,

20

,

float

(

"inf"

)

]

,

    labels

=

[

"Low activity"

,

"Fair"

,

"Active"

,

"High activity"

]

)

print

(

"User activity level distribution:"

)

print

(

user_events

[

"Activity level"

]

.

value_counts

(

)

)


Conversion funnel analysis

Conversion path

Example

Count users by event type

funnel

=

events.

groupby

(

"Event type"

)

[

"User ID"

]

.

nunique

(

)

funnel

=

funnel.

reindex

(

[

"Browse"

,

"Click"

,

"Favorite"

,

"Add to cart"

,

"Place order"

,

"Comment"

]

)

Calculate conversion rate

funnel_df

=

pd.

DataFrame

(

{

   

"Number of users"

: funnel

,

   

"Absolute conversion rate"

:

(

funnel / funnel

[

"Browse"

]

100

)

.

round

(

2

)

,

   

"Step conversion rate"

:

(

funnel / funnel.

shift

(

1

)

100

)

.

round

(

2

)

}

)

.

fillna

(

100

)

print

(

"=== Conversion funnel ===\n"

)

print

(

funnel_df

)

print

(

)

Visualize funnel data

print

(

"Funnel data:"

)

for

step

,

row

in

funnel_df.

iterrows

(

)

:

   

print

(

f

"{step}: {row['Number of users']} people ({row['Absolute conversion rate']:.1f}%)"

)


Channel analysis

Performance by channel

Example

Channel user analysis

channel_analysis

=

events.

groupby

(

"Channel"

)

.

agg

(

{

   

"User ID"

:

"nunique"

,

   

"Event ID"

:

"count"

}

)

.

rename

(

columns

=

{

   

"User ID"

:

"Number of users"

,

   

"Event ID"

:

"Number of events"

}

)

channel_analysis

[

"Events per user"

]

=

(

    channel_analysis

[

"Number of events"

]

/ channel_analysis

[

"Number of users"

]

)

.

round

(

2

)

print

(

"=== Channel analysis ===\n"

)

print

(

channel_analysis

)

print

(

)

Channel conversion comparison

channel_funnel

=

events

[

events

[

"Event type"

]

.

isin

(

[

"Browse"

,

"Place order"

]

)

]

.

groupby

(

   

[

"Channel"

,

"Event type"

]

)

[

"User ID"

]

.

nunique

(

)

.

unstack

(

)

channel_funnel

[

"Conversion Rate"

]

=

(

    channel_funnel

[

"Place order"

]

/ channel_funnel

[

"Browse"

]

100

)

.

round

(

2

)

print

(

"Conversion rate by channel:"

)

print

(

channel_funnel

)


Device analysis

Example

Device analysis

device_analysis

=

events.

groupby

(

"Device"

)

.

agg

(

{

   

"User ID"

:

"nunique"

,

   

"Event ID"

:

"count"

}

)

.

rename

(

columns

=

{

   

"User ID"

:

"Number of users"

,

   

"Event ID"

:

"Number of events"

}

)

device_analysis

[

"Events per user"

]

=

(

    device_analysis

[

"Number of events"

]

/ device_analysis

[

"Number of users"

]

)

.

round

(

2

)

print

(

"=== Device distribution ===\n"

)

print

(

device_analysis

)

print

(

)

Device conversion rate

device_funnel

=

events

[

events

[

"Event type"

]

.

isin

(

[

"Browse"

,

"Place order"

]

)

]

.

groupby

(

   

[

"Device"

,

"Event type"

]

)

[

"User ID"

]

.

nunique

(

)

.

unstack

(

)

device_funnel

[

"Conversion Rate"

]

=

(

    device_funnel

[

"Place order"

]

/ device_funnel

[

"Browse"

]

100

)

.

round

(

2

)

print

(

"Conversion rate by device:"

)

print

(

device_funnel

)

Retention analysis

Example

Simplified retention analysis

Assume that being active within 7 days after registration counts as retained

users_with_events

=

events.

groupby

(

"User ID"

)

[

"Event time"

]

.

agg

(

[

"min"

,

"max"

]

)

users_with_events.

columns

=

[

"First active"

,

"Last active"

]

Merge registration information

users_analysis

=

users.

merge

(

users_with_events

,

left_on

=

"User ID"

,

right_index

=

True

,

how

=

"left"

)

Calculate active days

users_analysis

[

"Active days"

]

=

(

    users_analysis

[

"Last active"

]

[

"First active"

]

)

.

dt

.

days

1

print

(

"=== User retention analysis ===\n"

)

print

(

f

"Users with activity: {len(users_with_events)}"

)

print

(

f

"Average active days: {users_analysis['Active days'].mean():.1f} days"

)

print

(

)

Next-day retention (simplified)

retention_1d

=

len

(

users_analysis

[

users_analysis

[

"Active days"

]

=

2

]

)

/

len

(

users_analysis

)

100

retention_3d

=

len

(

users_analysis

[

users_analysis

[

"Active days"

]

=

3

]

)

/

len

(

users_analysis

)

100

print

(

f

"Next-day retention rate: {retention_1d:.1f}%"

)

print

(

f

"3-day retention rate: {retention_3d:.1f}%"

)

Analysis summary

Example

print

(

"""
=== User Behavior Analysis Summary ===

  1. User engagement
       - Event types are dominated by browsing, followed by clicks
       - The average number of events per user is low, so user stickiness needs improvement

  2. Conversion funnel
       - There is significant drop-off, so the user experience needs optimization
       - The conversion rate from browsing to placing an order is low

  3. Channel effectiveness
       - It is recommended to focus on optimizing the conversion path of high-traffic channels
       - Performance varies across channels, requiring refined operations

  4. Device performance
       - Mobile is the main device, so the mobile experience should be a key focus

  5. Optimization Suggestions
       - 1) Optimize product display to improve browse-to-click conversion
       - 2) Simplify the shopping process to reduce order drop-off
       - 3) Optimize page loading speed for mobile
       - 4) Establish a user segmentation operation system
    """

)