如何在不同日期添加针对性细胞的NaT数据帧



我想将属性单元格值的Nat从excel转换为不同的日期。首先我检查Nat,然后我想覆盖到新的日期。但数据帧中没有发生覆盖,下面的错误消息打印为

if pd.isnull(df_TS.loc['Name']['Actual_date']):
df_TS['Name']['Actual_date'] =  pd.to_datetime(new_date) 
print(df_TS['Name']['Actual_date'])

Error:
Traceback (most recent call last):
File "C:Userslk38988AppDataLocalProgramsPythonPython38libsite-packagespandascoreindexesbase.py", line 2898, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libsindex.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libsindex.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libshashtable_class_helper.pxi", line 1675, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libshashtable_class_helper.pxi", line 1683, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 253
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:Python_scriptsUTAS_BPCU_WAS_updation_Ver3.py", line 173, in <module>
df_TS[each_TS][temp_actual_date] =  start_date #df_TS[each_TS][temp_actual_date].fillna(end_date)
File "C:Userslk38988AppDataLocalProgramsPythonPython38libsite-packagespandascoreframe.py", line 2906, in __getitem__
indexer = self.columns.get_loc(key)
File "C:Userslk38988AppDataLocalProgramsPythonPython38libsite-packagespandascoreindexesbase.py", line 2900, in get_loc
raise KeyError(key) from err
KeyError: 253

使用loc方法的想法是正确的。

但您似乎忽略了Pandas是一种所谓的数组语言的方式。也就是说,每个操作都应用于整列,而不是单独应用于每列中的值。所以在Pandas中很少使用if,因为它是一个标量运算符。

让我们以玩具为例。在这里,我们创建了一个数据帧,其中三行由id字段索引,另一列存储日期时间。

import pandas as pd
df_TS = pd.DataFrame([dict(id=1, actual_date='2020-12-23'),
dict(id=2, actual_date=None),
dict(id=3, actual_date=None)])
df_TS = df_TS.set_index('id')
df_TS['actual_date'] = pd.to_datetime(df_TS['actual_date'])

以下是它的样子:

id
12020-12-23
2
3

最新更新