9951 explained code solutions for 126 technologies


python-pandasHow to set data frame index


import pandas as pd

df = pd.DataFrame({
  'Id':    [1, 10, 12, 15, 34],
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

df = df.set_index('Id')ctrl + c
import pandas as pd

load Pandas module

pd.DataFrame

creates Pandas DataFrame object

.set_index(

uses specified column as index for dataframe rows

'Id'

column to use as index


Usage example

import pandas as pd

df = pd.DataFrame({
  'Id':    [1, 10, 12, 15, 34],
  'Phone': ['ip5', 'ip6', 'ip8', 'sms', 'xi'],
  'Phone Price': [204, 304, 404, 405, 305]
})

print(df)

df = df.set_index('Id')

print(df)
output
   Id Phone  Phone Price
0   1   ip5          204
1  10   ip6          304
2  12   ip8          404
3  15   sms          405
4  34    xi          305
   Phone  Phone Price
Id                   
1    ip5          204
10   ip6          304
12   ip8          404
15   sms          405
34    xi          305