gpt4 book ai didi

python - 从多索引 Pandas 系列创建 1 列数据框

转载 作者:行者123 更新时间:2023-11-28 22:09:54 24 4
gpt4 key购买 nike

我有一个像这样的多索引系列:

Year  Month
2012 1 444
2 222
3 333
4 1101

我想变成:

Date      Value
2012-01 444
2012-02 222
2012-03 333
2012-04 1101

绘制一条线。

我已经尝试了 series.unstack(level=0)series.unstack(level=1),但这会创建一个矩阵

In[1]: series.unstack(level=0)
Out[1]:
Year 2012 2013 2014 2015 2016 2017 2018
Month
1 444 ... ... ... ... ... ...
2 222 ... ... ... ... ... ...
3 333 ... ... ... ... ... ...
4 1101 ... ... ... ... ... ...

我错过了什么?

最佳答案

使用Index.to_frameto_datetime如果还添加了 Day 列并重新分配回来,则工作:

s.index = pd.to_datetime(s.index.to_frame().assign(Day=1))
print (s)
2012-01-01 444
2012-02-01 222
2012-03-01 333
2012-04-01 1101
Name: a, dtype: int64

对于一列 DataFrame 使用 Series.to_frame :

df1 = s.to_frame('Value')
print (df1)
Value
2012-01-01 444
2012-02-01 222
2012-03-01 333
2012-04-01 1101

如果需要PeriodIndex 添加Series.dt.to_period :

s.index = pd.to_datetime(s.index.to_frame().assign(Day=1)).dt.to_period('m')
print (s)
2012-01 444
2012-02 222
2012-03 333
2012-04 1101
Freq: M, Name: a, dtype: int64

df2 = s.to_frame('Value')
print (df2)
Value
2012-01 444
2012-02 222
2012-03 333
2012-04 1101

关于python - 从多索引 Pandas 系列创建 1 列数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com