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
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
@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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.