如何在标题中的1个单元格中加入2个单元格?

时间:2017-04-25 08:55:30

标签: python pandas

enter image description here

以上是我的数据框,我希望将其放在标题

enter image description here

有人对此有所了解吗?

1 个答案:

答案 0 :(得分:2)

您可以使用:

a = ['201701', '', '201705', '', '201707']
b = ['PHI', 'Actual', 'Actual', 'PHI', 'Actual']
data = [[np.nan, np.nan, np.nan, 8, np.nan]]
df = pd.DataFrame(data, index=['ClassCold'], columns = pd.MultiIndex.from_arrays([a,b]))
print (df.columns)
MultiIndex(levels=[['', '201701', '201705', '201707'], ['Actual', 'PHI']],
           labels=[[1, 0, 2, 0, 3], [1, 0, 0, 1, 0]])

print (df)
          201701        201705     201707
             PHI Actual Actual PHI Actual
ClassCold    NaN    NaN    NaN   8    NaN

get_level_values获取MultiIndex的第一级,to_series转换为Seriesreplace空字符串(或空格)转换为NaN并按ffill转发填充NaN

上次新建MultiIndex from_arrays

a = df.columns.get_level_values(0).to_series().replace('',np.nan).ffill()
df.columns = df.columns = pd.MultiIndex.from_arrays([a, df.columns.get_level_values(1)])
print (df)
          201701        201705     201707
             PHI Actual Actual PHI Actual
ClassCold    NaN    NaN    NaN   8    NaN

print (df.columns)
MultiIndex(levels=[['201701', '201705', '201707'], ['Actual', 'PHI']],
           labels=[[0, 0, 1, 1, 2], [1, 0, 0, 1, 0]])