Reputation: 14057
how to get data from this form (long representation of data):
import pandas as pd
df = pd.DataFrame({
'c0': ['A','A','B'],
'c1': ['b','c','d'],
'c2': [1, 3,4]})
print(df)
Out:
c0 c1 c2
0 A b 1
2 A c 3
3 B d 4
to this form :
c0 c1 c2
0 A b 1
2 A c 3
3 A d NaN
4 B b NaN
5 B c NaN
6 B d 4
Is long to wide to long transformation the only approach to doing this?
Upvotes: 2
Views: 153
Reputation: 294488
method 1
unstack
and stack
df.set_index(['c0', 'c1']).unstack().stack(dropna=False).reset_index()
method 2
reindex
with product
df.set_index(['c0', 'c1']).reindex(
pd.MultiIndex.from_product([df.c0.unique(), df.c1.unique()], names=['c0', 'c1'])
).reset_index()
Upvotes: 5