简体   繁体   中英

How to pivot this using pandas?

I'm totally new to python/pandas so please bear with me.

I have been trying for what seems like an eternity to rearrange my dataframe (see the numbers beside in/out...). I have read several answers to what seem like similar questions on stack overflow but I can't get anything to work for me.

Initially I had a table that looked like this: intial table

I want to make it look like this (but with the actual dates and values):

company--date--date--date--date

ebay--------val-----val---val----val

amazon----val-----val---val----val

Initially I thought I could use df.pivot but then I didn't know what to put for index= because I didn't have a name for the columns. So I figured out how to give them a name using

df.columns.names = 'Company'

Now I have a table like this: table as it is now

Based on other answers I've seen on this site I tried again to use df.pivot 1.with index = 'Company' and I get KeyError: 'Company' 2.also with index = ['Company'] also get KeyError: 'Company'

Can anyone tell me what it is that I'm doing wrong?

Thanks in advance for your help

Think you mean 'transpose' not 'pivot'. Can you please try doing the following? df1.T . Full example below from pandas.DataFrame.transpose

setup:

d1 = {'col1': [1, 2], 'col2': [3, 4]}
df1 = pd.DataFrame(data=d1)
df1

output:

   col1  col2
0     1     3
1     2     4

code:

df1.T # or df1.transpose()

output:

      0  1
col1  1  2
col2  3  4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM