Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据Pandas中另一列的标准比较同一列中的日期?_Python_Python 3.x_Pandas - Fatal编程技术网

Python 如何根据Pandas中另一列的标准比较同一列中的日期?

Python 如何根据Pandas中另一列的标准比较同一列中的日期?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个带有u_id、日期、订单的df,我需要添加一个列,为每个用户提供每个订单之间的日期差。例如: u_id | date | order 001 | 2019-01-01 | 1 001 | 2019-01-10 | 2 001 | 2019-01-15 | 3 002 | 2019-05-03 | 1 002 | 2019-05-06 | 2 ... 我的目标是: u_id | date | order | date_difference 00

我有一个带有u_id、日期、订单的df,我需要添加一个列,为每个用户提供每个订单之间的日期差。例如:

u_id | date       | order
001  | 2019-01-01 |  1
001  | 2019-01-10 |  2
001  | 2019-01-15 |  3
002  | 2019-05-03 |  1
002  | 2019-05-06 |  2
...
我的目标是:

u_id | date       | order | date_difference
001  | 2019-01-01 |  1    |    NaT
001  | 2019-01-10 |  2    |   9 days
001  | 2019-01-15 |  3    |   5 days
002  | 2019-05-03 |  1    |    NaT
002  | 2019-05-06 |  2    |   3 days
...
date\u difference
col不一定要说天


我将pandas与python 3.6一起使用。

您可以执行
groupby

df['date_difference'] = df.groupby('u_id')['date'].diff()
或不带
groupby
,只要顺序正确:

df['date_difference'] = df.date.diff().where(df.u_id==df.u_id.shift())
输出:

   u_id       date  order date_difference
0     1 2019-01-01      1             NaT
1     1 2019-01-10      2          9 days
2     1 2019-01-15      3          5 days
3     2 2019-05-03      1             NaT
4     2 2019-05-06      2          3 days

df['date\u difference']=df.groupby('u id')['date'].diff()
完成了任务,谢谢!不错的一款,diff和shift将派上用场