python - Reshaping pandas DataFrame from long to wide while adding many columns -
i have long dataframe df
in following format:
user_id day action1 action2 action3 action4 action5 1 0 4 2 0 1 0 1 1 4 2 0 1 0 2 1 4 2 0 1 0
the values in action columns represent number of times user took action on day. translate wide dataframe
able extend time frame arbitrarily (say, 365 days).
i can reshape wide with:
df_indexed = df.set_index(['user_id', 'day']) df_wide = df_indexed.unstack().fillna()
how go adding remaining 358 days filled 0 each of 5 actions?
you can use multiindexed dataframe, create new index itertools.product
combining users dataframe , days want, , replace index filling missing values 0.
import itertools users = df.user_id.unique() df_indexed = df.set_index(['user_id', 'day']) index = pd.multiindex.from_tuples(list(itertools.product(users, range(365)))) reindexed = df_indexed.reindex(index, fill_value=0)
Comments
Post a Comment