如何将具有单级列的现有数据框转换为具有分层索引列 (MultiIndex)?
示例数据框:
In [1]:
import pandas as pd
from pandas import Series, DataFrame
df = DataFrame(np.arange(6).reshape((2,3)),
index=['A','B'],
columns=['one','two','three'])
df
Out [1]:
one two three
A 0 1 2
B 3 4 5
我原以为 reindex() 会起作用,但我得到了 NaN:
In [2]:
df.reindex(columns=[['odd','even','odd'],df.columns])
Out [2]:
odd even odd
one two three
A NaN NaN NaN
B NaN NaN NaN
如果我使用 DataFrame() 也一样:
In [3]:
DataFrame(df,columns=[['odd','even','odd'],df.columns])
Out [3]:
odd even odd
one two three
A NaN NaN NaN
B NaN NaN NaN
如果我指定 df.values,最后一种方法确实有效:
In [4]:
DataFrame(df.values,index=df.index,columns=[['odd','even','odd'],df.columns])
Out [4]:
odd even odd
one two three
A 0 1 2
B 3 4 5
这样做的正确方法是什么?为什么 reindex() 会给出 NaN?