Change Column To Multi-index By Using One Column As A New Level
I've got a DataFrame: df = pd.DataFrame.from_dict({'Close': {1: 14.03, 3: 14.02, 0: 79.88, 2: 80.31}, 'High': {1: 14.3, 3: 14.33, 0: 80.22, 2: 81.19}, 'Low': {1: 14.03, 3: 13.99,
Solution 1:
Use DataFrame.set_index
with DataFrame.unstack
, then DataFrame.swaplevel
with DataFrame.sort_index
:
df = df.set_index('Code', append=True).unstack().swaplevel(1, 0, axis=1).sort_index(axis=1)
print (df)
Code A2M CBA \
Close High Low OpenValue Volume Close High Low
014.0314.3014.0314.1823244651.461656782.079.8880.2279.39114.0214.3313.9914.2531533209.182249159.080.3181.1980.25
Code
OpenValue Volume
079.791.131286e+081416232.0180.971.303258e+081622784.0
Solution 2:
We can also use your index
to use GroupBy.first
:
df.groupby(['Code',df.index]).first().unstack('Code').swaplevel(axis=1).sort_index(axis=1)
Code A2M CBA \
Close High Low OpenValue Volume Close High Low
014.0314.3014.0314.1823244651.461656782.079.8880.2279.39114.0214.3313.9914.2531533209.182249159.080.3181.1980.25
Code
OpenValue Volume
079.791.131286e+081416232.0180.971.303258e+081622784.0
Post a Comment for "Change Column To Multi-index By Using One Column As A New Level"