transpose()函数有助于转置DataFrame的索引和列。它通过将行写为列,反之亦然,沿着主对角线反映DataFrame。

语法

DataFrame.transpose(*args, **kwargs)  

参数

copy:如果其值为True,则正在复制基础数据。否则,默认情况下,如果可能,不进行复制。

*args, **kwargs:都是附加关键字,不会影响,但具有接受numpy的兼容性。

返回值

它返回转置后的DataFrame。

示例1

# 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)  

输出

                           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 

示例2

# 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)     

输出

          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

标签: Pandas, Pandas教程, Pandas库, Pandas基础, Pandas学习, Pandas使用, Pandas指南, Pandas入门教程, Pandas模块, Pandas数据库, Pandas实战教程, Pandas用法总结, Pandas文档