Enigmatic
Enigmatic

Reputation: 4148

Why am I unable to add a column name to a data frame?

My Target

I'd like to add/replace a column name while also removing Name, dtype at the end of the data frame

Data Frame

>>> df

0  Cheese
1  Bread
2  Ham
3  Egg
Name: Column1, dtype: object

My Attempt

I have tried to do the following:

df.columns = ['Cart']

But when outputting df, it appears exactly the same as before hand.

Expected Output

   Cart
0  Cheese
1  Bread
2  Ham
3  Egg

Upvotes: 2

Views: 145

Answers (2)

piRSquared
piRSquared

Reputation: 294218

@jezrael's answer is your answer. I just like to add alternatives

Construct from scratch given your df is a pd.Series

pd.DataFrame(dict(Cart=df))

Upvotes: 2

jezrael
jezrael

Reputation: 862471

df is Series, not DataFrame.

Use Series.to_frame:

df.to_frame('Cart')

Or:

df.rename('Cart').to_frame()

df = pd.Series(['Cheese','Bread','Ham','Egg'], name='Column1')
print (df)
0    Cheese
1     Bread
2       Ham
3       Egg
Name: Column1, dtype: object

print (type(df))
<class 'pandas.core.series.Series'>

print (df.to_frame('Cart'))
     Cart
0  Cheese
1   Bread
2     Ham
3     Egg

Upvotes: 3

Related Questions