在已旋转的Dataframe中加入两列

时间:2016-08-23 19:08:44

标签: python pandas join dataframe pivot

我正在尝试加入两个列(年份和季度)。我已从sql中提取数据并将其旋转,如下所示:

df3 = pd.pivot_table(df, index=["Year", "Q"], columns='Area', values="Lows", aggfunc=np.sum, fill_value=0)

我现在想将列YearQ一起加入图表,但我的索引似乎搞砸了。以下是数据框的显示方式。

Before:
Year   Q
2003   1
       2
       3
       4
2004   1
       2

Desired output:
Period 
2003 1
2003 2
2003 3
2003 4

1 个答案:

答案 0 :(得分:1)

这应该有效:

df3.index = df3.index.to_series().apply(lambda x: ' '.join([str(y) for y in x]))

更通用

join = lambda x, delim=' ': delim.join([str(y) for y in x])

df3.index = df3.index.to_series().apply(join, delim=' ')