C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Pandas DataFrame.transpose()The transpose() function helps to transpose the index and columns of the dataframe. It reflects DataFrame over its main diagonal by writing the rows as columns and vice-versa. SyntaxDataFrame.transpose(*args, **kwargs) Parameterscopy: If its value is True, then the underlying data is being copied. Otherwise, by default, no copy is made, if possible. *args, **kwargs: Both are additional keywords that do not affect, but has an acceptance that provide compatibility with a numpy. ReturnsIt returns the transposed DataFrame. Example1
# importing pandas as pd
import pandas as pd
# Creating the DataFrame
info = pd.DataFrame({'Weight':[27, 44, 38, 10, 67],
'Name':['William', 'John', 'Smith', 'Parker', 'Jones'],
'Age':[22, 17, 19, 24, 27]})
# Create the index
index_ = pd.date_range('2010-10-04 06:15', periods = 5, freq ='H')
# Set the index
info.index = index_
# Print the DataFrame
print(info)
# return the transpose
result = info.transpose()
# Print the result
print(result)
Output Weight Name Age
2010-10-04 06:15:00 27 William 22
2010-10-04 07:15:00 44 John 7
2010-10-04 08:15:00 38 Smith 19
2010-10-04 09:15:00 10 Parker 24
2010-10-04 10:15:00 67 Jones 27
2010-10-04 06:15:00 2010-10-04 07:15:00 2010-10-04 08:15:00 \
Weight 27 44 38
Name William John Smith
Age 22 7 19
2010-10-04 09:15:00 2010-10-04 10:15:00
Weight 10 67
Name Parker Jones
Age 24 27
Example2
# importing pandas as pd
import pandas as pd
# Creating the DataFrame
info = pd.DataFrame({"A":[8, 2, 7, None, 6],
"B":[4, 3, None, 9, 2],
"C":[17, 42, 35, 18, 24],
"D":[15, 18, None, 11, 12]})
# Create the index
index_ = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5']
# Set the index
info.index = index_
# Print the DataFrame
print(info)
# return the transpose
result = info.transpose()
# Print the result
print(result)
Output A B C D
Row_1 8.0 4.0 17 15.0
Row_2 2.0 3.0 42 18.0
Row_3 7.0 NaN 35 NaN
Row_4 NaN 9.0 18 11.0
Row_5 6.0 2.0 24 12.0
Row1 Row2 Row3 Row4 Row5
A 8.0 2.0 7.0 NaN 6.0
B 4.0 3.0 NaN 9.0 2.0
C 17.0 42.0 35.0 18.0 24.0
D 15.0 18.0 NaN 11.0 12.0
Next TopicDataFrame.where()
|