pandas库中的列与索引之间的转换

本文转载于 https://www.cnblogs.com/hhh5460/p/7067928.html

准备数据

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
这里写图片描述

列–>索引

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

则转为下图,此时列被date索引代替:

这里写图片描述

索引–>列

df.reset_index() # (all)index 改为 column
  • 1
这里写图片描述

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注