Search code examples
pandasdataframeconcatenation

Renaming Columns after concatenating two Series with same Column names


I have two series namely x and y.

x:

Index Timestamp
0 2022-11-16 13:00:00
1 2022-11-17 13:48:00

y:

Index Timestamp
0 2022-11-16 19:13:00
1 2022-11-17 16:21:00

I combine these two series into a data frame as follows.

z = pd.concat([x, y], axis=1)

But in the dataframe both the column names appear as "Timestamp". I want to rename it. When I used the below code it changes both column names at the same time.

mapping = {z.columns[0]: 'Start' }
su = z.rename(columns=mapping)

Preferred output:

start End
2022-11-16 13:00:00 2022-11-16 19:13:00
2022-11-17 13:48:00 2022-11-17 16:21:00

How can I do this in pandas?


Solution

  • Example

    x = pd.Series({0: '2022-11-16 13:00:00', 1: '2022-11-17 13:48:00'}, name='Timestamp')
    y = pd.Series({0: '2022-11-16 19:13:00', 1: '2022-11-17 16:21:00'}, name='Timestamp')
    

    Code

    pd.concat([x, y], keys=['start', 'end'], axis=1)
    

    result:

        start               end
    0   2022-11-16 13:00:00 2022-11-16 19:13:00
    1   2022-11-17 13:48:00 2022-11-17 16:21:00