Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将系列的索引更改为索引的连接标签名称?_Python_Pandas - Fatal编程技术网

Python 如何将系列的索引更改为索引的连接标签名称?

Python 如何将系列的索引更改为索引的连接标签名称?,python,pandas,Python,Pandas,我有一个像这样的系列 ser: profit 2003-01 5 2003-02 5 2003-03 5 我想取代码执行的ser的累积和 profit.cumsum()。现在我希望ser的索引如下所示。不幸的是,在使用cumsum() 非常感谢那些愿意回答的人 使用列表理解和f-strings以及if-else进行处理: df.index = [x if i == 0 else f'{df.index[0]} to {x}' for i, x in enum

我有一个像这样的系列

ser:
         profit
2003-01    5
2003-02    5
2003-03    5
我想取代码执行的ser的累积和
profit.cumsum()
。现在我希望
ser
的索引如下所示。不幸的是,在使用
cumsum()


非常感谢那些愿意回答的人

使用列表理解和
f-string
s以及if-else进行处理:

df.index = [x if i == 0 else f'{df.index[0]} to {x}' for i, x in enumerate(df.index)]
print (df)
                    profit
2003-01                  5
2003-01 to 2003-02       5
2003-01 to 2003-03       5
或:

df.index = [x if i == 0 else f'{df.index[0]} to {x}' for i, x in enumerate(df.index)]
print (df)
                    profit
2003-01                  5
2003-01 to 2003-02       5
2003-01 to 2003-03       5
df.index = np.hstack((df.index[0], df.index[0] + ' to ' + df.index[1:]))
print (df)
                    profit
2003-01                  5
2003-01 to 2003-02       5
2003-01 to 2003-03       5