Python Pandas复制的列没有出现在头部

时间:2018-04-05 15:17:54

标签: python pandas

我正在尝试向我的DataFrame添加两个新列,这些列是当前列的副本,但是尽管看到我的head()方法的输出显示列作为我的DataFrame的一部分,但是当我运行{{1他们没有出现的方法。我是否使用正确的命令来更新我的DataFrame,并在新名称下重复两列?我通过jupyter notebooks运行所有这些命令

Current Column -> New Column (Duplicate of Current Column)
'date' -> 'ts'
'y' -> 'clicks'

代码:

import pandas as pd
import numpy as np
from fbprophet import Prophet

df = pd.read_csv('car-sales-raw-data.csv')

allDf = df
allDf = allDf.fillna(0)
allDf['date'] = pd.to_datetime(allDf['date'])

allDf.head()
""" OUTPUT """
        date        day_of_week leads clicks  cars
    181 2017-07-01  Saturday    44    611     26
    182 2017-07-02  Sunday      30    203     14
    183 2017-07-05  Wednesday   55    994     25
    184 2017-07-06  Thursday    50    2854    23
    185 2017-07-07  Friday      78    850     52

# duplicate date and click columns

allDf.assign(ds = allDf['date'])
allDf.assign(y = allDf['clicks'])
allDf.head()

""" OUTPUT """
            date        day_of_week leads clicks  cars
        181 2017-07-01  Saturday    44    611     26
        182 2017-07-02  Sunday      30    203     14
        183 2017-07-05  Wednesday   55    994     25
        184 2017-07-06  Thursday    50    2854    23
        185 2017-07-07  Friday      78    850     52

1 个答案:

答案 0 :(得分:1)

您实际上已将列分配给数据框,但您不会存储更新的数据框。为此,请使用以下代码行

allDf

         date      day_of_week  leads   clicks  cars
181     2017-07-01  Saturday    44      611     26
182     2017-07-02  Sunday      30      203     14
183     2017-07-05  Wednesday   55      994     25
184     2017-07-06  Thursday    50      2854    23
185     2017-07-07  Friday      78      850     52

allDf = allDf.assign(ds = allDf['date'])

allDf

           date     day_of_week     leads   clicks  cars    ds
181     2017-07-01  Saturday        44      611     26  2017-07-01
182     2017-07-02  Sunday          30      203     14  2017-07-02
183     2017-07-05  Wednesday       55      994     25  2017-07-05
184     2017-07-06  Thursday        50      2854    23  2017-07-06
185     2017-07-07  Friday          78      850     52  2017-07-07