python - 为什么我无法将列名称添加到数据框中?

标签 python python-2.7 pandas dataframe

我的目标

我想添加/替换列名称,同时删除数据框末尾的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

最佳答案

dfSeries,而不是 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/

相关文章:

python - 在非标准位置构建支持 SSL 的 Python

python - 无法在 Python 2.7.9 虚拟环境中导入 _winreg

api - 错误youtube v3 python响应未准备好

python - 将列名作为变量传递给 python/pandas 函数中的 select 语句

python - 基于一列元素对两个数组进行排序和连接

python - 使用 mdates 和 matplotlib 将 x 轴设置为日期

python - 如何在ubuntu中使用python自动连接到SSH?

python - 为什么 Django 表单在波斯语中显示 UnicodeEncodeError?

Python:读取和写入 CSV 文件

Django 查询返回空值