How to switch columns rows in a pandas dataframe
You can use df = df.T
to transpose the dataframe. This switches the dataframe round so that the rows become columns.
You could also use pd.DataFrame.transpose()
.
How to transpose/pivot and group columns to rows in Pandas Dataframe?
Try this:
res = (df.melt(id_vars='Date', var_name='Sales_Type',value_name='Sales')
.sort_values('Date')
.reset_index(drop=True))
print(res)
Date Sales_Type Sales
0 date1 Sales1 1.1
1 date1 Sales2 1.2
2 date1 Sales3 1.3
3 date2 Sales1 2.1
4 date2 Sales2 2.2
5 date2 Sales3 2.3
6 date3 Sales1 3.1
7 date3 Sales2 3.2
8 date3 Sales3 3.3
How to transpose dataframe columns into rows in pandas
use melt
:
df.melt(id_vars=['country','year','perc'])
older versions of Pandas:
pd.melt(df, id_vars=['country','year','perc'])
Output:
country year perc variable value
0 IN 2015 hjk data1 75
1 US 2015 KTM data1 100
2 IN 2015 hjk data2 81
3 US 2015 KTM data2 289
4 IN 2015 hjk data3 96
5 US 2015 KTM data3 632
Option #2
df.set_index(['country','year','perc']).stack().reset_index()
Output:
country year perc level_3 0
0 IN 2015 hjk data1 75
1 IN 2015 hjk data2 81
2 IN 2015 hjk data3 96
3 US 2015 KTM data1 100
4 US 2015 KTM data2 289
5 US 2015 KTM data3 632
move column in pandas dataframe
You can rearrange columns directly by specifying their order:
df = df[['a', 'y', 'b', 'x']]
In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.
>>> df[[c for c in df if c not in ['b', 'x']]
+ ['b', 'x']]
a y b x
0 1 -1 2 3
1 2 -2 4 6
2 3 -3 6 9
3 4 -4 8 12
To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:
cols_at_end = ['b', 'x']
df = df[[c for c in df if c not in cols_at_end]
+ [c for c in cols_at_end if c in df]]
Pandas: How can I move certain columns into rows?
You can form two dataframe using pd.melt
first and combine it back to become one dataframe.
df1 = df.melt(id_vars=['uid', 'location'], value_vars=['unit1_price', 'unit2_price', 'unit3_price'],var_name='unit',value_name='price')
df2 = df.melt(id_vars=['uid', 'location'], value_vars=['unit1_vol', 'unit2_vol', 'unit3_vol'],var_name='unit', value_name="volume")
ddf = pd.concat([df1,df2['volume']],axis=1).sort_values(by=['uid','unit'],ignore_index=True)
ddf['unit']=ddf['unit'].str.split('_',expand=True)[0]
Related Topics
I'm Getting "Typeerror: 'List' Object Is Not Callable". How to Fix This Error
How to Control the Mouse in MAC Using Python
In Python, How Does One Catch Warnings as If They Were Exceptions
Convert Bytes to Bits in Python
How to Get All of the Output from My .Exe Using Subprocess and Popen
Catch Exception and Continue Try Block in Python
Spark Iteration Time Increasing Exponentially When Using Join
Importerror: No Module Named <Something>
How to Rotate a Matplotlib Plot Through 90 Degrees
Repeat Rows in Data Frame N Times
Region: Ioerror: [Errno 22] Invalid Mode ('W') or Filename
How to Replace (Or Strip) an Extension from a Filename in Python
How to Set Selenium Webdriver from Headless Mode to Normal Mode Within the Same Session
How to Do N-D Distance and Nearest Neighbor Calculations on Numpy Arrays
Re.Sub Erroring with "Expected String or Bytes-Like Object"