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