简体   繁体   English

从第二个 Pandas Pandas dataframe 中减去 groupby 后的一个日期时间列,每个组的时间参考

[英]Substract one datetime column after a groupby with a time reference for each group from a second Pandas dataframe

I have one dataframe df1 with one admissiontime for each id.我有一个 dataframe df1,每个 ID 都有一个入场时间。

id     admissiontime    
1      2117-04-03 19:15:00  
2      2117-10-18 22:35:00  
3      2163-10-17 19:15:00  
4      2149-01-08 15:30:00  
5      2144-06-06 16:15:00  

And an another dataframe df2 with several datetame for each id还有一个 dataframe df2,每个 id 都有几个 datetame

id      datetime        
1       2135-07-28 07:50:00.000         
1       2135-07-28 07:50:00.000         
2       2135-07-28 07:57:15.900             
3       2135-07-28 07:57:15.900         
3       2135-07-28 07:57:15.900     

I would like to substract for each id, datetimes with his specific admissiontime, in a column of the second dataframe.我想在第二个 dataframe 的列中减去每个 ID、日期时间和他的具体入场时间。

I think I have to use d2.group.by('id')['datetime']- something but I struggle to connect with the df1.我想我必须使用 d2.group.by('id')['datetime']- 但我很难连接到 df1。

Use Series.sub with mapping by Series.map by another DataFrame :Series.sub与另一个DataFrameSeries.map映射一起使用:

 df1['admissiontime'] = pd.to_datetime(df1['admissiontime'])
 df2['datetime'] = pd.to_datetime(df2['datetime'])

df2['diff'] = df2['datetime'].sub(df2['id'].map(df1.set_index('id')['admissiontime']))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 日期/时间:对于 dataframe 的每个子集,将日期时间列增加一秒 - date/time: increment the datetime column by one second for each subset of dataframe 使用 Pandas,根据第二列的最小值从数据框中的一列(对于每组)获取值 - With Pandas, get value from one column in dataframe (for each group), based on minimum value of second column Pandas DataFrame:按列分组,按日期时间排序,按条件截断分组 - Pandas DataFrame: Groupby Column, Sort By DateTime, and Truncate Group by Condition 用熊猫在一列中减去每两行 - substract each two row in one column with pandas 在pandas数据框中的groupby之后选择每个组中的前3个类别 - Select top 3 categories in each group after groupby in pandas dataframe Pandas:在数据帧组之后重新采样时间组名称 - Pandas: resample time group names after a dataframe groupby 使用 pandas.DataFrame.groupby 从每组中获取最大值 - Get the max value from each group with pandas.DataFrame.groupby 熊猫:有一个datetime列,需要将每个单元格减去4秒 - Pandas: have a datetime column, need to substract 4 seconds to each cell pandas:groupby并计算每组中第一个元素的时差 - pandas: groupby and calculate time difference from first element in each group 在pandas groupby之后对每组进行采样 - Sample each group after pandas groupby
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM