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

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.set_index('site')
  7. --------------------------------------------------------------------
  8. age price color
  9. site
  10. google 18 1.0 red
  11. baidu 39 2.0 black
  12. wiki 22 3.0 None
  13. pandas 45 4.0 red

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.set_index(['site', 'age'])
  7. --------------------------------------------------------------------
  8. price color
  9. site age
  10. google 18 1.0 red
  11. baidu 39 2.0 black
  12. wiki 22 3.0 None
  13. pandas 45 4.0 red

Example

  1. import pandas as pd
  2. df = pd.DataFrame({'site':['google', 'baidu', 'wiki', 'pandas'],
  3. 'age':[18, 39, 22, 45],
  4. 'price': [1.0, 2.0, 3.0, 4.0],
  5. 'color': ['red', 'black', None, 'red']}, index=['first', 'second', 'third', 'forth'])
  6. df.set_index([pd.Index(['a', 'b', 'c', 'd'])])
  7. ------------------------------------------------------------
  8. site age price color
  9. a google 18 1.0 red
  10. b baidu 39 2.0 black
  11. c wiki 22 3.0 None
  12. d pandas 45 4.0 red