Python中的 pandas.DataFrame.T()函数
pandas.DataFrame.T属性用于转置数据框的索引和列。属性 T 以某种方式与方法transpose() 相关。此属性的主要函数是通过将行作为列来创建数据框在主对角线上的反射,反之亦然。
Syntax: DataFrame.T
Parameters:
copy: If True, the underlying data is copied, otherwise (default).
*args, **kwargs: Additional keywords
Returns: The Transposed data frame
示例 1:
有时我们需要对数据框进行转置,以便更准确地研究它。在这种情况下,pandas.DataFrame.T属性起着重要的作用。
Python3
# Importing pandas module
import pandas as pd
# Creating a dictionary
dit = {'August': [10, 25, 34, 4.85, 71.2, 1.1],
'September': [4.8, 54, 68, 9.25, 58, 0.9],
'October': [78, 5.8, 8.52, 12, 1.6, 11],
'November': [100, 5.8, 50, 8.9, 77, 10]}
# Converting it to data frame
df = pd.DataFrame(data=dit)
# Original DataFrame
df
Python3
# Transposing the data frame
# using dataframe.T property
df_trans = df.T
print("Transposed Data frame :")
df_trans
Python3
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['Harvey.', 10.5, 45.25, 95.2],
['Carson', 15.2, 54.85, 50.8],
['juli', 14.9, 87.21, 60.4],
['Ricky', 20.3, 45.23, 99.5],
['Gregory', 21.1, 77.25, 90.9],
['Jessie', 16.4, 95.21, 10.85]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age', 'Percentage', 'Accuracy'],
index=['a', 'b', 'c', 'd', 'e', 'f'])
# print dataframe.
df
Python3
# Transposing the data frame
# using dataframe.T property
df_trans = df.T
print("Transposed Data frame :")
df_trans
输出:
转置数据框。
蟒蛇3
# Transposing the data frame
# using dataframe.T property
df_trans = df.T
print("Transposed Data frame :")
df_trans
输出:
在上面的示例中,我们转置了具有数值/内容的数据框 'df'。
示例 2:
蟒蛇3
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['Harvey.', 10.5, 45.25, 95.2],
['Carson', 15.2, 54.85, 50.8],
['juli', 14.9, 87.21, 60.4],
['Ricky', 20.3, 45.23, 99.5],
['Gregory', 21.1, 77.25, 90.9],
['Jessie', 16.4, 95.21, 10.85]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age', 'Percentage', 'Accuracy'],
index=['a', 'b', 'c', 'd', 'e', 'f'])
# print dataframe.
df
输出:
转置数据帧。
蟒蛇3
# Transposing the data frame
# using dataframe.T property
df_trans = df.T
print("Transposed Data frame :")
df_trans
输出:
在上面的例子中,我们转置了混合了数据类型的数据框“df”。