5

Given the dataframe df

df = pd.DataFrame([1,2,3,4])
print(df)
   0
0  1
1  2
2  3
3  4

I would like to modify it as

print(df)
   0
A  1
A  2
A  3
A  4
2
  • 5
    Why would you want an index that is not unique? This seems redundant to me. Additionally indexing will be problematic Commented Oct 4, 2017 at 14:31
  • 2
    On the face of it, this is a bad idea (See EdChum's comment). Giving you the benefit of the doubt, maybe this is a part in a larger process that you feel you need to accomplish in order to get the larger task completed. If that is True then there is certainly a way to better accomplish that task without doing this. Otherwise, we are just trying to accomplish parlor tricks. Commented Oct 4, 2017 at 14:35

3 Answers 3

11

In this specific case you can use:

df.index = ['A'] * len(df)
Sign up to request clarification or add additional context in comments.

Comments

6

Use set_index

In [797]: df.set_index([['A']*len(df)], inplace=True)

In [798]: df
Out[798]:
   0
A  1
A  2
A  3
A  4

1 Comment

Don't use inplace=True, always be explicit and reassign. inplace does a copy anyway.
2

When you create the df, you can add it.

df = pd.DataFrame([1,2,3,4],index=['A']*4)
df
Out[325]: 
   0
A  1
A  2
A  3
A  4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.