I have a wide dataframe in Python Pandas like this:
import pandas as pd
import numpy as np
df = pd.DataFrame({'student_id' :[100, 101, 102],
'q1.cta1_count':[0, 1, 1],
'q1.cta1_date' :[np.nan, '2019-03-26', '2019-03-25' ],
'q1.cta1.reminder_count' :[0, 1, 0],
'q1.cta1.reminder_date' :[np.nan, '2019-03-31', np.nan]})
df
and I need to convert to the long format so that it looks like this dataframe:
# student_id type count date
# 100 q1.cta1 0 NaN
# 100 q1.cta1.reminder 0 NaN
# 101 q1.cta1 1 2019-03-26
# 101 q1.cta1.reminder 1 2019-03-31
# 102 q1.cta1 1 2019-03-25
# 102 q1.cta1.reminder 0 NaN
How can I do that?
You can use pandas wide to long, but first you need to reshape the columns to fit pandas wide to long format :
Now, you can reshape your data :
Alternatively, you could use pyjanitor's pivot_longer function, which is built on pandas' melt function, and offers some more flexibility (full disclosure, I am a contributor to the library):