我的目标
我想添加/替换列名称,同时删除数据框末尾的Name, dtype
数据框
>>> df
0 Cheese
1 Bread
2 Ham
3 Egg
Name: Column1, dtype: object
我的尝试
我尝试执行以下操作:
df.columns = ['Cart']
但是当输出df
时,它看起来和之前一模一样。
预期输出
Cart
0 Cheese
1 Bread
2 Ham
3 Egg
最佳答案
df
是 Series
,而不是 DataFrame
。
使用Series.to_frame
:
df.to_frame('Cart')
或者:
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
关于python - 为什么我无法将列名称添加到数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418636/