Pandas DataFrame.transpose()使用示例

transpose()函数有助于转置数据帧的索引和列。通过将行写为列, 反之亦然, DataFrame在其主要对角线上反映了DataFrame。
句法

DataFrame.transpose(*args, **kwargs)

参数
【Pandas DataFrame.transpose()使用示例】复制:如果其值为True, 则将复制基础数据。否则, 默认情况下, 如果可能, 不进行任何复制。
* args, ** kwargs:两者都是不影响但具有接受能力的附加关键字, 它们与numpy兼容。
Return
它返回转置的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 indexinfo.index = index_# Print the DataFrame print(info) # return the transpose result = info.transpose()# Print the result print(result)

输出
WeightNameAge2010-10-04 06:15:0027William222010-10-04 07:15:0044John72010-10-04 08:15:0038Smith192010-10-04 09:15:0010Parker242010-10-04 10:15:0067Jones272010-10-04 06:15:00 2010-10-04 07:15:00 2010-10-04 08:15:00\Weight274438NameWilliamJohnSmithAge227192010-10-04 09:15:00 2010-10-04 10:15:00Weight1067NameParkerJonesAge2427

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

输出
ABCDRow_18.04.01715.0Row_22.03.04218.0Row_37.0NaN35NaNRow_4NaN9.01811.0Row_56.02.02412.0Row1Row2Row3Row4Row5A8.02.07.0NaN6.0B4.03.0NaN9.02.0C17.042.035.018.024.0D15.018.0NaN11.012.0

    推荐阅读