将列添加到Dataframe KeyError:'2019-12-07 21:19:17'

时间:2019-12-18 14:40:51

标签: python pandas

我有一个数据框df,看起来像:

    Name
0   John
1  Sarah 
2  Harry 
3    Bob
4     Jo
5  Steve
6    Leo 
7  Nigel

我正在尝试添加一个名为Last_Paid的列,新列中的所有行均包含上次修改薪资文件的日期。

所需的输出如下:

    Name            Last_Paid
0   John  2019-12-07 21:19:17
1  Sarah  2019-12-07 21:19:17
2  Harry  2019-12-07 21:19:17
3    Bob  2019-12-07 21:19:17
4     Jo  2019-12-07 21:19:17
5  Steve  2019-12-07 21:19:17
6    Leo  2019-12-07 21:19:17
7  Nigel  2019-12-07 21:19:17

我用来添加带有日期的列的代码如下:

 modTimesinceEpoc = os.path.getmtime(PayFilepath)
 LastmodificationTimePayfile = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modTimesinceEpoc))
 df['Last_Paid'] = df[LastmodificationTimePayfile]

但是我得到了key error

KeyError: '2019-12-07 21:19:17'

'2019-12-07 21:19:17'LastmodificationTimePayfile变量的值

如果有人能让我知道如何添加具有该值的新列,将不胜感激。

请参阅下面的完整错误消息:

  File "<ipython-input-13-48aa2b889a2a>", line 1, in <module>
    runfile('C:/Database/Standardised Joined Q1 and Pay/2016_Q1/join.py', wdir='C:/Database/Standardised Joined Q1 and Pay/2016_Q1')

  File "C:\Anaconda_Python 3.7\2019.03\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda_Python 3.7\2019.03\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Database/Standardised Joined Q1 and Pay/2016_Q1/join.py", line 198, in <module>
    main()

  File "C:/Database/Standardised Joined Q1 and Pay/2016_Q1/join.py", line 85, in main
    result['PAY_LAST_MODIFIED'] = result[LastmodificationTimePayfile]

  File "C:\Anaconda_Python 3.7\2019.03\lib\site-packages\pandas\core\frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Anaconda_Python 3.7\2019.03\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 127, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 153, in pandas._libs.index.IndexEngine._get_loc_duplicates

  File "pandas/_libs/index.pyx", line 170, in pandas._libs.index.IndexEngine._maybe_get_bool_indexer

KeyError: '2019-12-07 21:19:17'

1 个答案:

答案 0 :(得分:1)

LastmodificationTimePayfile的值不是数据框的一列,因此是键错误。

如果要将新列的值设置为LastmodificationTimePayfile的值,则应写

df['Last_Paid'] = LastmodificationTimePayfile