DataFrame.set_index
DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
使用现有列设置DataFrame的索引。
Parameters
keys | 此参数可以是单个列键、与调用DataFrame长度相同的单个数组或是包含列键和数组任意组合的列表。 |
---|---|
drop | 删除要用作新索引的列。 |
append | 是否将列附加到现有索引 |
inplace | False:返回一个副本;True:就地执行操作并返回None |
verify_integrity | 检查新索引是否有重复项 |
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
df.set_index('site')
--------------------------------------------------------------------
age price color
site
google 18 1.0 red
baidu 39 2.0 black
wiki 22 3.0 None
pandas 45 4.0 red
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
df.set_index(['site', 'age'])
--------------------------------------------------------------------
price color
site age
google 18 1.0 red
baidu 39 2.0 black
wiki 22 3.0 None
pandas 45 4.0 red
Example
import pandas as pd
df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
'age':[18, 39, 22, 45],
'price': [1.0, 2.0, 3.0, 4.0],
'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
df.set_index([pd.Index(['a', 'b', 'c', 'd'])])
------------------------------------------------------------
site age price color
a google 18 1.0 red
b baidu 39 2.0 black
c wiki 22 3.0 None
d pandas 45 4.0 red