简体   繁体   中英

Python - simple dataframe restructuring

I am struggling to restructure my dataframe in a simple and effective way.

The first dataframe 'new' is what I have and the desired dataframe is new2. I have been messing around with pivot, stack, unstack, set_index, reshape etc for a long time and still can't achieve this simple transformation. I keep getting either error messages or the wrong outcome. Could someone please help out?

What I have

data1 = [50, 60]
data2 = [100, 200]
year = [2015,2016]
new = pd.DataFrame({'product': data1, 'year':year, 'market':data2})

What I want

new2 = pd.DataFrame(columns = ['2015', '2016'])
new2.loc['market'] = data1
new2.loc['product'] = data2

desired outcome

You need set_index with T and last for remove column name add rename_axis :

df = df.set_index('year').T.rename_axis(None, axis=1)
print (df)
         2015  2016
market    100   200
product    50    60

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