-1

I have a list called partylist which prints the following.

Index(['AAAP', 'AABHAP', 'AACP', 'AAHPty', 'AAM', 'AAPP', 'ABD', 'ABEP',
       'ABGP', 'ABHM',
       ...
       'kajp', 'mimm', 'pjdl', 'rajpt', 'ravp', 'rpsn', 'skd', 'ssrd', 'svjn',
       'swbi'],
      dtype='object', name='PARTY', length=671)

I tried using reset_index

newlist = partylist.reset_index(level=['PARTY'], inplace=True)

but got an error


AttributeError Traceback (most recent call last) /var/folders/l9/6n1gmxmx515cfndb3gm2cyv40000gn/T/ipykernel_12124/2959807225.py in ----> 1 newlist = partylist.reset_index(level=['PARTY'], inplace=True)

AttributeError: 'Index' object has no attribute 'reset_index'

How can I solve it and make a column list of the partylist?

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 2
    You have an `Index`. What do you mean "make a column"? You're trying to turn the index into a Series? Into a DataFrame? Add it to an existing DataFrame? – Henry Ecker Aug 15 '21 at 22:23
  • as henry said, it's not clear why you only have a standalone `Index` or what you want to do with it, but it sounds like maybe you want `partylist.to_series()` or `partylist.to_frame()` – tdy Aug 15 '21 at 22:41
  • 2
    side note: you should not use `inplace=True` *and* assign the result at the same time. use only one or the other, not both. i suggest using the assignment method, as `inplace=True` is not recommended anymore. – tdy Aug 15 '21 at 22:43
  • Dare I say it, but this is one of those questions where a screenshot of the dataframe would actually help! lol. – MDR Aug 15 '21 at 22:47

2 Answers2

1

Looks like you ran this line at some point:

df = df.set_index('PARTY')

Since the name='PARTY' bit is there you can make the index a column again with:

df = df.reset_index()

If you want to rename the index (say to 'PARTYLIST') and move it to a column try:

df = df.reset_index().rename(columns={df.index.name:'PARTYLIST'})

The above assumes your dataframe is called df - change as required.

MDR
  • 2,610
  • 1
  • 8
  • 18
  • 1
    hmm interesting, are you saying the following code turns `df` into a pure `Index` on your end? `df=pd.DataFrame({'PARTY':[4,2,7]}); df=df.set_index('PARTY')` – tdy Aug 16 '21 at 01:58
  • 1
    after those commands, `df` is still a `DataFrame` on my end (pandas 1.3.1) – tdy Aug 16 '21 at 01:59
0

I think your error is reproducible with this code

df = pd.DataFrame({1: [1,2,3]})
df.index = ['A', 'B', 'C']
df.index.reset_index()

You are calling reset_index() on an Index object - as the error says it doesn't have that attribute. That's because this method is for dataframes as per the docs.

To create a column containing the index object contained in your partylist variable, you need to first convert it to a list and then assign it to a column with this syntax:

df['your_column'] = list(partylist)
osint_alex
  • 952
  • 3
  • 16