Values of a column in Pandas as columns while keeping the last update

Viewed 51

I have the following Pandas dataframe.

timestamp label value
1          a     1
2          b     2
3          a     5
4          b     0
5          c     3

Is there a way to convert the values of the label column into columns and keep the last used data as values? It does not matter if I assign Null or 0 in the missing values that have not appeared yet.

timestamp  a   b     c
1          1   Null  Null
2          1   2     Null
3          5   2     Null
4          5   0     Null
5          5   0     3
2 Answers

Use pivot_table and forward filling:

df.pivot_table(index="timestamp", columns="label", values="value").fillna(method="ffill")

Output

label        a    b    c
timestamp               
1          1.0  NaN  NaN
2          1.0  2.0  NaN
3          5.0  2.0  NaN
4          5.0  0.0  NaN
5          5.0  0.0  3.0

unstack and ffill

df.set_index(['timestamp','label'])['value'].unstack().ffill()

label        a    b    c
timestamp               
1          1.0  NaN  NaN
2          1.0  2.0  NaN
3          5.0  2.0  NaN
4          5.0  0.0  NaN
5          5.0  0.0  3.0
Related