agrajag_42
agrajag_42

Reputation: 165

Pivot and rename Pandas dataframe

I have a dataframe in the format

      Date         Datediff         Cumulative_sum
01 January 2019       1                   5
02 January 2019       1                   7
02 January 2019       2                   15
01 January 2019       2                   8
01 January 2019       3                   13

and I want to pivot the column Datediff from the dataframe such that the end result looks like

Index            Day-1    Day-2    Day-3
01 January 2019    5        8        13
02 January 2019    7        15

I have used the pivot command shuch that

pt = pd.pivot_table(df, index = "Date",
                   columns = "Datediff",
                   values = "Cumulative_sum") \
               .reset_index() \
               .set_index("Date"))

which returns the pivoted table

                   1        2         3
01 January 2019    5        8        13
02 January 2019    7        15

And I can then rename rename the columns using the loop

for column in pt:
    pt.rename(columns = {column : "Day-" + str(column)}, inplace = True)

which returns exactly what I want. However, I was wondering if there is a faster way to rename the columns when pivoting and get rid of the loop altogether.

Upvotes: 3

Views: 2867

Answers (1)

jezrael
jezrael

Reputation: 862511

Use DataFrame.add_prefix:

df.add_prefix('Day-')

In your solution:

pt = (pd.pivot_table(df, index = "Date",
                   columns = "Datediff",
                   values = "Cumulative_sum")
        .add_prefix('Day-'))

Upvotes: 7

Related Questions