Как транспонировать кадр данных Pandas без индекса
Вы можете использовать следующий синтаксис для переноса кадра данных pandas и исключения индекса:
df.set_index('first_col'). T
Это просто устанавливает первый столбец DataFrame в качестве индекса, а затем выполняет транспонирование.
В следующем примере показано, как использовать этот синтаксис на практике.
Пример: транспонирование Pandas DataFrame без индекса
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9
Если мы транспонируем DataFrame, значения индекса будут отображаться вверху:
#transpose DataFrame df.T 0 1 2 3 4 5 team A B C D E F points 18 22 19 14 14 11 assists 5 7 7 9 12 9
Чтобы транспонировать DataFrame без индекса, мы можем сначала использовать функцию set_index() :
#transpose DataFrame without index df.set_index('team'). T team A B C D E F points 18 22 19 14 14 11 assists 5 7 7 9 12 9
Обратите внимание, что значения индекса больше не отображаются в верхней части транспонированного кадра данных.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные задачи в pandas:
pandas.DataFrame.transpose#
Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose() .
Parameters : *args tuple, optional
Accepted for compatibility with NumPy.
copy bool, default False
Whether to copy the data after transposing, even for DataFrames with a single dtype.
Note that a copy is always required for mixed dtype DataFrames, or for DataFrames with any extension types.
The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.
You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True
Returns : DataFrame
The transposed DataFrame.
Permute the dimensions of a given array.
Transposing a DataFrame with mixed dtypes will result in a homogeneous DataFrame with the object dtype. In such a case, a copy of the data is always made.
Square DataFrame with homogeneous dtype
>>> d1 = 'col1': [1, 2], 'col2': [3, 4]> >>> df1 = pd.DataFrame(data=d1) >>> df1 col1 col2 0 1 3 1 2 4
>>> df1_transposed = df1.T # or df1.transpose() >>> df1_transposed 0 1 col1 1 2 col2 3 4
When the dtype is homogeneous in the original DataFrame, we get a transposed DataFrame with the same dtype:
>>> df1.dtypes col1 int64 col2 int64 dtype: object >>> df1_transposed.dtypes 0 int64 1 int64 dtype: 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 kids 0 Alice 9.5 False 0 1 Bob 8.0 True 0
>>> df2_transposed = df2.T # or df2.transpose() >>> df2_transposed 0 1 name Alice Bob score 9.5 8.0 employed False True kids 0 0
When the DataFrame has mixed dtypes, we get a transposed DataFrame with the object dtype:
>>> df2.dtypes name object score float64 employed bool kids int64 dtype: object >>> df2_transposed.dtypes 0 object 1 object dtype: object
pandas.DataFrame.transpose¶
Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. The property T is an accessor to the method transpose() .
copy : bool, default False
If True, the underlying data is copied. Otherwise (default), no copy is made if possible.
*args, **kwargs
Additional keywords have no effect but might be accepted for compatibility with numpy.
DataFrame
The transposed DataFrame.
numpy.transpose Permute the dimensions of a given array.
Transposing a DataFrame with mixed dtypes will result in a homogeneous DataFrame with the object dtype. In such a case, a copy of the data is always made.
Square DataFrame with homogeneous dtype
>>> d1 = 'col1': [1, 2], 'col2': [3, 4]> >>> df1 = pd.DataFrame(data=d1) >>> df1 col1 col2 0 1 3 1 2 4
>>> df1_transposed = df1.T # or df1.transpose() >>> df1_transposed 0 1 col1 1 2 col2 3 4
When the dtype is homogeneous in the original DataFrame, we get a transposed DataFrame with the same dtype:
>>> df1.dtypes col1 int64 col2 int64 dtype: object >>> df1_transposed.dtypes 0 int64 1 int64 dtype: 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 kids 0 Alice 9.5 False 0 1 Bob 8.0 True 0
>>> df2_transposed = df2.T # or df2.transpose() >>> df2_transposed 0 1 name Alice Bob score 9.5 8 employed False True kids 0 0
When the DataFrame has mixed dtypes, we get a transposed DataFrame with the object dtype:
>>> df2.dtypes name object score float64 employed bool kids int64 dtype: object >>> df2_transposed.dtypes 0 object 1 object dtype: object
Pandas dataframe — транспонирование столбцов
которая группирует строки по ‘пользователю’ и группирует столбцы по ‘месяцу’.
valueX valueY month 2013-01 2013-02 2013-01 2013-02 user 884 1 7 5 29 889 9 0 38 15
Примечание: Столбцы теперь являются многоуровневым индексом, например, чтобы получить значение valueX для пользователя 889 в 2013-01 году, вам нужно сделать следующее: df2.loc[889, (‘valueX’, ‘2013-01’)] , или для всех дат: df2.loc[889, (‘valueX’, slice(None))]