[英]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 我想添加/替换列名,同时还要删除数据框末尾的Name, dtype
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. 但是当输出df
,它看起来与以前完全一样。
Expected Output 预期产量
Cart
0 Cheese
1 Bread
2 Ham
3 Egg
df
is Series
, not DataFrame
. df
是Series
,而不是DataFrame
。
Use Series.to_frame
: 使用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. @jezrael的答案就是您的答案。 I just like to add alternatives 我只是想添加替代品
Construct from scratch given your df
is a pd.Series
假设df
是pd.Series
,请从头开始pd.Series
pd.DataFrame(dict(Cart=df))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.