Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Ctrl+K

pandas.DataFrame.transpose#

DataFrame.transpose(*args,copy=False)[source]#

Transpose index and columns.

Reflect the DataFrame over its main diagonal by writing rows as columnsand vice-versa. The propertyT is an accessor to the methodtranspose().

Parameters:
*argstuple, optional

Accepted for compatibility with NumPy.

copybool, default False

Whether to copy the data after transposing, even for DataFrameswith a single dtype.

Note that a copy is always required for mixed dtype DataFrames,or for DataFrames with any extension types.

Note

Thecopy keyword will change behavior in pandas 3.0.Copy-on-Writewill be enabled by default, which means that all methods with acopy keyword will use a lazy copy mechanism to defer the copy andignore thecopy keyword. Thecopy keyword will be removed in afuture version of pandas.

You can already get the future behavior and improvements throughenabling copy on writepd.options.mode.copy_on_write=True

Returns:
DataFrame

The transposed DataFrame.

See also

numpy.transpose

Permute the dimensions of a given array.

Notes

Transposing a DataFrame with mixed dtypes will result in a homogeneousDataFrame with theobject dtype. In such a case, a copy of the datais always made.

Examples

Square DataFrame with homogeneous dtype

>>>d1={'col1':[1,2],'col2':[3,4]}>>>df1=pd.DataFrame(data=d1)>>>df1   col1  col20     1     31     2     4
>>>df1_transposed=df1.T# or df1.transpose()>>>df1_transposed      0  1col1  1  2col2  3  4

When the dtype is homogeneous in the original DataFrame, we get atransposed DataFrame with the same dtype:

>>>df1.dtypescol1    int64col2    int64dtype: object>>>df1_transposed.dtypes0    int641    int64dtype: object

Non-square DataFrame with mixed dtypes

>>>d2={'name':['Alice','Bob'],...'score':[9.5,8],...'employed':[False,True],...'kids':[0,0]}>>>df2=pd.DataFrame(data=d2)>>>df2    name  score  employed  kids0  Alice    9.5     False     01    Bob    8.0      True     0
>>>df2_transposed=df2.T# or df2.transpose()>>>df2_transposed              0     1name      Alice   Bobscore       9.5   8.0employed  False  Truekids          0     0

When the DataFrame has mixed dtypes, we get a transposed DataFrame withtheobject dtype:

>>>df2.dtypesname         objectscore       float64employed       boolkids          int64dtype: object>>>df2_transposed.dtypes0    object1    objectdtype: object

[8]ページ先頭

©2009-2025 Movatter.jp