lassence.net

Field notes from the AI frontier

Pivot pandas Dataframes with non-numeric values

--- archive: codebook, 2020–2023 · topic: Pandas ---

Setup

# Import libraries
import pandas as pd
import numpy as np

# Sample DataFrame
df = pd.DataFrame({
    'advertiser':['Alice', 'Alice', 'Alice', 'Alice', 'Bob', 'Bob', 'Bob', 'Charlie', 'Charlie', 'Charlie'],
    'keyword': ['screen', 'phone', 'laptop', 'keyboard', 'phone', 'tablet', 'flat', 'screen', 'phone', 'computer'],
    'clicks': np.random.randint(low=20, high=50, size=10)
})
df
advertiserkeywordclicks
0Alicescreen34
1Alicephone46
2Alicelaptop34
3Alicekeyboard36
4Bobphone24
5Bobtablet33
6Bobflat25
7Charliescreen35
8Charliephone25
9Charliecomputer35

Pivot keywords to columns

# Pivot keywords to columns
(
    df
    .pivot(index='advertiser', columns='keyword', values='clicks')
)
keywordcomputerflatkeyboardlaptopphonescreentablet
advertiser
AliceNaNNaN36.034.046.034.0NaN
BobNaN25.0NaNNaN24.0NaN33.0
Charlie35.0NaNNaNNaN25.035.0NaN
# Pivot keywords to columns, ranked by clicks
(
    df
    .sort_values('clicks', ascending=False)
    .groupby('advertiser')
    .agg(list)
    .apply(lambda x: pd.Series(x['keyword']), axis=1)
)
0123
advertiser
Alicephonekeyboardscreenlaptop
BobtabletflatphoneNaN
CharliescreencomputerphoneNaN