1

I have the following DataFrame built:

 Movies Cost Tickets 0 1158 0.000000 2.000000 1 1158 0.000000 0.000000 2 1158 0.000000 0.000000 3 1158 0.000000 3.000000 

I've used stack() to change my configuration to:

 Event 1 0 Movies 1158 1 Cost 0.000000 2 Tickets 2.000000 3 Movies 1158 4 Cost 0.000000 5 Tickets 0.000000 6 Movies 1158 7 Cost 0.000000 8 Tickets 0.000000 9 Movies 1158 10 Cost 0.000000 11 Tickets 3.000000 

but this is stacking the data top of each other, I was looking to create a new column with the end goal being:

 Event 1 Event 2 Event 3 Event 4 0 Movies 1158 1158 1158 1158 1 Cost 0.000000 0.000000 0.000000 0.000000 2 Tickets 2.000000 0.000000 0.000000 3.000000 

here is my current configuration:

df = pd.DataFrame({ 'Tickets': pd.Series(Tickets), 'Movies': pd.Series(Movies), 'Cost': pd.Series(costs)}) print(df) df.columns.name = '' stackEvent3 = df.stack() stackEvent3 = df.stack().reset_index(level=0, drop=True).reset_index(name='Event1') 

Any guidance is greatly appreciated, thank you!

4
  • 3
    Would a transposition not work? df.T Commented Feb 21, 2020 at 22:32
  • 1
    I really new to Pandas, care to share an example? Commented Feb 21, 2020 at 22:33
  • please check my answer Commented Feb 21, 2020 at 22:45
  • I looked up transposition and this makes sense. Thank you! Commented Feb 21, 2020 at 22:53

1 Answer 1

2

Use DataFrame.transpose with DataFrame.add_prefix:

new_df = df.T.rename(columns=dict(zip(df.index, df.index+1))).add_prefix('Event ') Event 1 Event 2 Event 3 Event 4 Movies 1158.0 1158.0 1158.0 1158.0 Cost 0.0 0.0 0.0 0.0 Tickets 2.0 0.0 0.0 3.0 

to set columns name like you want DataFrame.rename building a dict to replace:

df.T.rename(columns=dict(zip(df.index, ['brown', 'purple', 'yellow', 'blue']))) 

or

new_df = df.T new_df.columns = ['brown', 'purple', 'yellow', 'blue'] 
Sign up to request clarification or add additional context in comments.

5 Comments

What if I wanted to change the Event Name to something more unique? Like brown, purple, yellow and blue. I notice this is adding a number to the columns that are being generated. Btw, thank you for the quick response!
then use new_df.columns = ['brown', 'purple', 'yellow', 'blue'] and drop add_prefix simply you could use : df.T.rename(columns=dict(zip(df.index, ['brown', 'purple', 'yellow', 'blue'])))
You sir have saved me from breaking my head. I am new to Pandas and been searching for half the morning. But I don't know those keywords to search. Again thank you so much for all help!
I am glad to help:) please consider accept the answer!
Sorry, got one more question. Let's say I want to do math by dividing Movies by Tickets and captures its result by adding a new row or column on depending on what's best. Would you recommend doing math before the transpose or after?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.