dataframe, set index from list

Question:

Is it possible when creating a dataframe from a list, to set the index as one of the values?

import pandas as pd

tmp = [['a', 'a1'], ['b',' b1']]

df = pd.DataFrame(tmp, columns=["First", "Second"])

        First  Second
0          a   a1
1          b   b1

And how I’d like it to look:

        First  Second
a          a   a1
b          b   b1
Asked By: vandelay

||

Answers:

>>> pd.DataFrame(tmp, columns=["First", "Second"]).set_index('First', drop=False)
      First Second
First             
a         a     a1
b         b     b1
Answered By: Alexander

If you don’t want index name:

df = pd.DataFrame(tmp, columns=["First", "Second"], index=[i[0] for i in tmp])

Result:

  First Second
a     a     a1
b     b     b1
Answered By: ragesz

Change it to list before assigning it to index

df.index = list(df["First"])
Answered By: Aman Singh Kamboj

set_axis

To set arbitrary values as the index, best practice is to use set_axis:

df = df.set_axis(['idx1', 'idx2'])

#       First  Second
# idx1      a      a1
# idx2      b      b1

set_index (list vs array)

It’s also possible to pass arbitrary values to set_index, but note the difference between passing a list vs array:


Why not just modify df.index directly?

Directly modifying attributes is fine and is used often, but using methods has its advantages:

  • Methods provide better error checking, e.g.:

    df = df.set_axis(['idx1', 'idx2', 'idx3'])
    
    # ValueError: Length mismatch: Expected axis has 2 elements, new values have 3 elements
    
    df.index = ['idx1', 'idx2', 'idx3']
    
    # No error despite length mismatch
    
  • Methods can be chained, e.g.:

    df.some_method().set_axis(['idx1', 'idx2']).another_method()
    
Answered By: tdy
import pandas as pd
tmp = [['a', 'a1'], ['b',' b1']]
df = pd.DataFrame(tmp, columns=["First", "Second"]).set_axis([tmp[0][0],tmp[1][0]])
df
Answered By: Ramsey A.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.