Linked Questions

Popular Questions

I have a dataframe that has id and week. I want to expand the dataframe so that each id have the same number of rows or four weeks.

import pandas as pd

data = {
    'id': ['a', 'a', 'b', 'c', 'c', 'c'],
    'week': ['1', '2', '3', '4', '3', '1'],
    'num1': [1, 3, 5, 4, 3, 6],
    'num2': [4, 5, 3, 4, 6, 6]
}
df = pd.DataFrame(data)
  id week  num1  num2
0  a    1     1     4
1  a    2     3     5
2  b    3     5     3
3  c    4     4     4
4  c    3     3     6
5  c    1     6     6

In pandas, I can just do:

df = (
    df.set_index(['id', 'week'])
      .unstack().stack(dropna=False)
      .reset_index()
)
   id week  num1  num2
0   a    1   1.0   4.0
1   a    2   3.0   5.0
2   a    3   NaN   NaN
3   a    4   NaN   NaN
4   b    1   NaN   NaN
5   b    2   NaN   NaN
6   b    3   5.0   3.0
7   b    4   NaN   NaN
8   c    1   6.0   6.0
9   c    2   NaN   NaN
10  c    3   3.0   6.0
11  c    4   4.0   4.0

How do you do this with polars?

Related Questions