📅  最后修改于: 2020-10-29 02:49:36             🧑  作者: Mango
transpose()函数有助于转置数据帧的索引和列。通过将行写为列,反之亦然,DataFrame在其主要对角线上反映了DataFrame。
DataFrame.transpose(*args, **kwargs)
copy:如果其值为True,则将复制基础数据。否则,默认情况下,如果可能,不进行任何复制。
* args,** kwargs:两者都是不影响但具有接受能力的附加关键字,它们与numpy兼容。
它返回转置的DataFrame。
# 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
# 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