snippetpythonCriticalCanonical
How to convert index of a pandas dataframe into a column
Viewed 0 times
indexcolumnhowdataframepandasconvertinto
Problem
How to convert an index of a dataframe into a column?
For example:
to
For example:
gi ptt_loc
0 384444683 593
1 384444684 594
2 384444686 596
to
index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
Solution
either:
or
If you have a multi-index frame with 3 levels of index, like:
and you want to convert the 1st (
df['index1'] = df.indexor
.reset_index:df = df.reset_index()If you have a multi-index frame with 3 levels of index, like:
>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303and you want to convert the 1st (
tick) and 3rd (obs) levels in the index into columns, you could do:>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303Code Snippets
df['index1'] = df.indexdf = df.reset_index()>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303Context
Stack Overflow Q#20461165, score: 1400
Revisions (0)
No revisions yet.