新添加的列在数据框中不起作用

我有一个数据框,在两列中,我在日期上做了一些不同:

difference=(df["date1"]-df["date2"]).dt.days

然后我尝试将它附加到现有数据框,我收到错误消息。如果我做:

df.assign(difference)

我得到:

TypeError: assign() takes 1 positional argument but 2 were given

如果我做:

df["Diference value"]=difference

我得到:

试图在 DataFrame 的切片副本上设置一个值。尝试.loc[row_indexer,col_indexer] = value改用

在这两种情况下,最后一行都填充了 NaN。

无论如何,我使用这个新的数据框,但是当我尝试 groupby (效果很好)时,get_group("Diference value")我得到:

> --------------------------------------------------------------------------- KeyError                                  Traceback (most recent call

> last) <ipython-input-46-71486a5f3be6> in <module>

> ----> 1 dias=sectores.get_group("Difference value")

> D:\ArchivosProgramas\Anaconda\envs\pandas_playground\lib\site-packages\pandas\core\groupby\groupby.py

> in get_group(self, name, obj)

>     685         inds = self._get_index(name)

>     686         if not len(inds):

> --> 687             raise KeyError(name)

>     688 

>     689         return obj._take_with_is_copy(inds, axis=self.axis)

> KeyError: 'Difference value'

我不知道错误从哪里开始以及如何解决。我只需要这个带有新列的数据框,然后正常进行分组。我整天都在试图解决它。任何帮助表示赞赏。谢谢。


达令说
浏览 122回答 2
2回答

暮色呼如

应该这样做:df['date1'] = pd.to_datetime(df['date1'])df['date2'] = pd.to_datetime(df['date2'])df['difference'] = (df['date1']-df['date2']).dt.daysprint(df)&nbsp; &nbsp; &nbsp; &nbsp;date1&nbsp; &nbsp; &nbsp; date2&nbsp; difference0 2020-02-28 2020-03-31&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;-32

慕侠2389804

请参见下面的示例:df.head()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;date1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;date20&nbsp; &nbsp;2020-01-07 08:24:25&nbsp; &nbsp; &nbsp;2020-07-28 01:34:441&nbsp; &nbsp;2020-01-06 10:32:18&nbsp; &nbsp; &nbsp;2020-03-21 17:13:072&nbsp; &nbsp;2020-01-07 08:34:01&nbsp; &nbsp; &nbsp;2020-03-21 17:13:093&nbsp; &nbsp;2020-05-02 11:13:18&nbsp; &nbsp; &nbsp;2020-07-18 21:57:114&nbsp; &nbsp;2020-01-11 12:56:22&nbsp; &nbsp; &nbsp;2020-04-02 21:28:15#creating diff column:df['diff']=(df["date1"]-df["date2"]).dt.daysdf.head()#it results on this:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;date1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; diff0&nbsp; &nbsp;2020-01-07 08:24:25&nbsp; &nbsp; &nbsp;2020-07-28 01:34:44&nbsp; &nbsp; &nbsp;2021&nbsp; &nbsp;2020-01-06 10:32:18&nbsp; &nbsp; &nbsp;2020-03-21 17:13:07&nbsp; &nbsp; &nbsp;752&nbsp; &nbsp;2020-01-07 08:34:01&nbsp; &nbsp; &nbsp;2020-03-21 17:13:09&nbsp; &nbsp; &nbsp;743&nbsp; &nbsp;2020-05-02 11:13:18&nbsp; &nbsp; &nbsp;2020-07-18 21:57:11&nbsp; &nbsp; &nbsp;774&nbsp; &nbsp;2020-01-11 12:56:22&nbsp; &nbsp; &nbsp;2020-04-02 21:28:15&nbsp; &nbsp; &nbsp;82
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python