Reputation: 761
I have a dataframe that looks like this:
In [32]: df
Out[32]:
200003 200003.1
0 123 456
I want to transform it like this:
200003
0 123
1 456
What is the easiest way to accomplish this?
Edit:
df.stack()
returns
0 200003 123
200003.1 456
dtype: int64
My goal is to use df.to_dict('records')
to be able to transform the df into a format suitable for machine learning like this [{'200003': '123'}, {'200003': '456'}]
Upvotes: 2
Views: 132
Reputation: 3897
I think you are looking for DataFrame.stack()
.
Answer to your edit:
stacked = df.stack()
stacked.index = [df.columns[0]] * stacked.shape[0]
and then:
out = [ {j[0]:j[1]} for j in list(zip(stacked.index, stacked.values)) ]
gives you the list of dicts you are looking for.
Upvotes: 1