0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pandas 転置後のindex 備忘録

Posted at

概要

転置(.T)後のindexについてハマったので残す。

  • 実施期間: 2024年11月
  • 環境:Windows11
  • Python: GoogleColabo

1. 転置前

DataFrameを用意する。このDataFrameのindexにnameプロパティを設定しなければ本備忘録は無視してよい。

import pandas as pd

# RangeIndex で名前が "index" の DataFrame を作成
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
df.index.name = "Index"

print(f'columns.name: {df.columns.name}')
print(f'index.name: {df.index.name}')
print(df.info())
columns.name: None
index.name: Index
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   A       3 non-null      int64
 1   B       3 non-null      int64
dtypes: int64(2)
memory usage: 176.0 bytes
None

{656DA692-07AE-4359-A1BD-FD82B4330103}.png

2. 転置後

df_T = df.T
print(f'columns.name: {df_T.columns.name}')
print(f'index.name: {df_T.index.name}')
print(df_T.info())
columns.name: Index
index.name: None
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, A to B
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   0       2 non-null      int64
 1   1       2 non-null      int64
 2   2       2 non-null      int64
dtypes: int64(3)
memory usage: 172.0+ bytes
None

{E05D30D8-CBE8-48F5-9C74-CBAAB74E84BC}.png

"Index"の文字の位置がいつもと違い「えっ?」となる。これは普段使わないcolmuns.nameというプロパティが置換前のindex.nameに置き換わったためでPandasの仕様である(らしいが公式Docには記載なし)。

3. nameプロパティの変更

気持ち悪いので明示的にnameを変更する。

df_T.columns.name = None
df_T.index.name = 'Index'   # 何でもよい
print(f'columns.name: {df_T.columns.name}')
print(f'index.name: {df_T.index.name}')
print(df_T.info())
columns.name: None
index.name: Index
<class 'pandas.core.frame.DataFrame'>
Index: 2 entries, A to B
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   0       2 non-null      int64
 1   1       2 non-null      int64
 2   2       2 non-null      int64
dtypes: int64(3)
memory usage: 172.0+ bytes
None

{9D260909-C4BA-4A97-BAF5-A4F96242C16B}.png

ちなみにdf_T.columns.name = Noneをしなければ、次のようになる。

{8C7172CE-A4DA-4F7E-A717-9AE7DEE9D348}.png

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?