Set a string as index of pandas DataFrame

Viewed 20354

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
3 Answers

In this specific case you can use:

df.index = ['A'] * len(df)

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

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
Related