【发布时间】:2021-04-27 10:24:34
【问题描述】:
我正在尝试将 6 个月的表格加入 Python 中的一个列中。但是我不确定为什么它给我带来这么多麻烦。有什么帮助吗?
df.Dates = df[["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]]
df.Dates = pd.to_datetime(df['Dates'],format='%Y-%m-%d %H:%M:%S')
print(df.Dates)
这是错误:
KeyError Traceback (most recent call last)
<ipython-input-23-83667cbe6215> in <module>
1 df.Dates = df[["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]]
----> 2 df.Dates = pd.to_datetime(df['Dates'],format='%Y-%m-%d %H:%M:%S')
3 print(df.Dates)
4 #Dates = df[["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]].apply(pd.Series.explode).sum(axis=1)
5 #print(Dates)
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2900 if self.columns.nlevels > 1:
2901 return self._getitem_multilevel(key)
-> 2902 indexer = self.columns.get_loc(key)
2903 if is_integer(indexer):
2904 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2895 return self._engine.get_loc(casted_key)
2896 except KeyError as err:
-> 2897 raise KeyError(key) from err
2898
2899 if tolerance is not None:
KeyError: 'Dates'
【问题讨论】:
-
你能添加一些示例数据吗? 3 行 3 列并添加预期输出?
-
第一行的右侧将为您提供无法在左侧使用 df.date 或 df['date'] 的数据框,它将无法正常工作。我猜你想连接所有这些列,请使用 str 方法
-
col_list = ["1 个月日期","2 个月日期","3 个月日期","4 个月日期","5 个月日期","6 个月日期"] df.Date = df.apply(lambda x: ''.join(str(x[col]) for col in col_list), axis=1)
标签: python pandas dataframe keyerror