Pandas 教程-Pandas DataFrame.transpose()
整理:python架构师
transpose()函数有助于转置DataFrame的索引和列。它通过将行写为列,反之亦然,沿着主对角线反映DataFrame。
语法
DataFrame.transpose(*args, **kwargs)
参数
copy:如果其值为True,则正在复制基础数据。否则,默认情况下,如果可能,不进行复制。
*args, **kwargs:都是附加关键字,不会影响,但具有接受numpy的兼容性。
返回值
它返回转置后的DataFrame。
示例1
# importing pandas as pdimport pandas as pd# Creating the DataFrameinfo = pd.DataFrame({'Weight':[27, 44, 38, 10, 67],'Name':['William', 'John', 'Smith', 'Parker', 'Jones'],'Age':[22, 17, 19, 24, 27]})# Create the indexindex_ = pd.date_range('2010-10-04 06:15', periods = 5, freq ='H')# Set the indexinfo.index = index_# Print the DataFrameprint(info)# return the transposeresult = info.transpose()# Print the resultprint(result)
专属福利 👉点击领取:最全Python资料合集
Weight Name Age2010-10-04 06:15:00 27 William 222010-10-04 07:15:00 44 John 72010-10-04 08:15:00 38 Smith 192010-10-04 09:15:00 10 Parker 242010-10-04 10:15:00 67 Jones 272010-10-04 06:15:00 2010-10-04 07:15:00 2010-10-04 08:15:00 \Weight 27 44 38Name William John SmithAge 22 7 192010-10-04 09:15:00 2010-10-04 10:15:00Weight 10 67Name Parker JonesAge 24 27
示例2
# importing pandas as pdimport pandas as pd# Creating the DataFrameinfo = 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 indexindex_ = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5']# Set the indexinfo.index = index_# Print the DataFrameprint(info)# return the transposeresult = info.transpose()# Print the resultprint(result)
A B C DRow_1 8.0 4.0 17 15.0Row_2 2.0 3.0 42 18.0Row_3 7.0 NaN 35 NaNRow_4 NaN 9.0 18 11.0Row_5 6.0 2.0 24 12.0Row1 Row2 Row3 Row4 Row5A 8.0 2.0 7.0 NaN 6.0B 4.0 3.0 NaN 9.0 2.0C 17.0 42.0 35.0 18.0 24.0D 15.0 18.0 NaN 11.0 12.0
热门推荐