Reputation: 145
I have a dataframe which looks like this
Wash_Month Wash_Day
0 3 2
1 4 3
I need to convert the same to this
Input Value
0 Wash_Month/Wash_Day 3,2
1 Wash_Month/Wash_Day 4,3
I tried merging the two columns but wasn't able to convert the column headers to row values
Thanks.
Upvotes: 1
Views: 3064
Reputation: 323396
Using groupby
with dict
d={'Wash_Month':'Wash_Month/Wash_Day','Wash_Day':'Wash_Month/Wash_Day'}
df.T.astype(str).groupby(d).agg(','.join).stack()
Out[319]:
Wash_Month/Wash_Day 0 3,2
1 4,3
Upvotes: 3
Reputation: 403258
This is a more efficient solution. I break down the steps:
# Compute the Value column with `agg`.
v = df.astype(str).agg(','.join)
# Compute the Input column with `df.columns.str.cat`
v.index = [df.columns.str.cat(sep='/')] * len(v)
# Reset the index.
v.rename_axis('Input').to_frame('Value').reset_index()
Input Value
0 Wash_Month/Wash_Day 3,2
1 Wash_Month/Wash_Day 4,3
Alternative (slower). Reshape your data a bit with stack
:
v = df.stack().astype(str).reset_index(level=1)
v.columns = ['Input', 'Value']
print(v)
Input Value
0 Wash_Month 3
0 Wash_Day 2
1 Wash_Month 4
1 Wash_Day 3
Look at the index(!). Now, call groupby
and agg
:
v.groupby(level=0).agg({'Input': '/'.join, 'Value':','.join})
Input Value
0 Wash_Month/Wash_Day 3,2
1 Wash_Month/Wash_Day 4,3
Upvotes: 3
Reputation: 294576
Here is cute way of doing it
pd.DataFrame(dict(
Input='/'.join(df),
Value=[*map(','.join, zip(*map(df.astype(str).get, df)))]
))
Input Value
0 Wash_Month/Wash_Day 3,2
1 Wash_Month/Wash_Day 4,3
Upvotes: 5