pandas 索引與列相互轉化

1. 準備數據

import pandas as pd
from io import StringIO


csv_txt = '''"date","player1","player2","score1","score2"
"2017-06-05","張繼科","林思遠",3,2
"2017-06-06","丁寧","劉思文",3,0
"2017-06-07","馬琳","樊振東",2,3
"2017-06-08","張燕","丁寧",0,3
"2017-06-09","張繼科","馬琳",3,2
"2017-06-10","劉思文","張燕",4,1
"2017-06-11","馬琳","林思遠",3,2
'''

#df = pd.read_csv(StringIO(csv_txt), header=0, index_col="date") # 以 date 做爲 index

df = pd.read_csv(StringIO(csv_txt), header=0) # 默認 index

2. 列 ——> 索引

  • df.set_index('date')
df.set_index('date', inplace=True) # column 改成 index

3. 索引 ——> 列

  • df['index'] = df.index
  • df.reset_index(level=0, inplace=True)
  • df.reset_index(level=['tick', 'obs'])
  • df['si_name'] = df.index.get_level_values('si_name') # where si_name is the name of the subindex.
df.reset_index() # (all)index 改成 column
#df.reset_index(level=0, inplace=True) # (the first)index 改成 column
相關文章
相關標籤/搜索