7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SeriesをDataframeに変換する際indexを列に追加する方法

Last updated at Posted at 2018-12-16

こんなところでなぜかすごく時間かかってしまったのでメモ。

#reset_index()を使う
SeriesのデータをDataframeに変換する際、indexを列として扱いたい!
結果から言うとreset_index()を使うだけ。

#適当にSeriesデータを作成
name = ["Red","Blue", "Green", "Yellow","Pink"]
num = "Num"
test = pd.Series(np.arange(1,6), index=name, name=num)

print(test)
#実行結果==========
Red       1
Blue      2
Green     3
Yellow    4
Pink      5
Name: Num, dtype: int64
#==================

#次にDaraframeに変換すると、こんなかんじでindexはそのままindexとなる。
pd.DataFrame(test)
#実行結果==========
	Num
Red	1
Blue	2
Green	3
Yellow	4
Pink	5

#==================

#よってreset_index()を使うと、下記の通り、indexを列として使えるようになった。
pd.DataFrame(test).reset_index()

#実行結果==========
  | index | Num |
| 0 | Red | 1 |
| 1 | Blue | 2 |
| 2 | Green | 3 |
| 3 | Yellow | 4 |
| 4 | Pink | 5 |

コードの実行結果をうまく表示するにはどうすればいいのか。。。

7
8
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
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?