【问题标题】:With Pandas, how do I subtract all recurring elements of a series with an element of another series?使用 Pandas,我如何用另一个系列的元素减去一个系列的所有重复元素?
【发布时间】:2020-10-14 15:15:07
【问题描述】:

我有一个这种类型的数据框:

    arr_time dep_time station
0   19:20:00 19:20:00 a
1   19:38:00 19:45:00 b
2   18:55:00 19:00:00 a
3   19:40:00 19:45:00 a
4   19:50:00 19:55:00 b 
.
.

我需要做的是: 对于 station 中的每个相同项目,用 arr_time 中的每个相关项目减去 dep_time 中的相关项目(不考虑相同项目)。例如: a

 for i in range(len(arr_time)):
      for j in range(len(dep_time)):
         if i != j:
            dep_time[j] - arr_time[i]

station a 的结果必须是:

result
-00:20:00
00:25:00

以此类推,适用于 station 中的所有站点。 由于数据量大,需要用 Pandas 编写。我会非常感谢任何可以帮助我的人!

【问题讨论】:

    标签: python pandas dataframe datetime subtraction


    【解决方案1】:

    这是一种方法。我使用pd.merge 将每个站点“a”链接到每个其他站点“a”(等等)。然后我进行了过滤,这样我们就不会将一个电台与它自己进行比较,并执行了时间算术。

    from io import StringIO
    import pandas as pd
    
    data = '''    arr_time dep_time station
    0   19:20:00 19:20:00 a
    1   19:38:00 19:45:00 b
    2   18:55:00 19:00:00 a
    3   19:40:00 19:45:00 a
    4   19:50:00 19:55:00 b 
    '''
    df = pd.read_csv(StringIO(data), sep='\s+')
    
    # create unique identifier for each row
    df['id'] = df.reset_index().groupby('station')['index'].rank(method='first').astype(int)
    
    # SQL-style self-join: all station 1's; all station 2's, etc.
    t = pd.merge(left=df, right=df, how='inner', on='station', suffixes=('_l', '_r'))
    
    # don't compare station to itself
    t = t[ t['id_l'] != t['id_r'] ] 
    
    # compute elapsed time (as timedelta object)
    t['elapsed'] = pd.to_timedelta(t['dep_time_l']) - pd.to_timedelta(t['arr_time_r'])
    
    # convert elapsed time to minutes (may not be necessary)
    t['elapsed'] = t['elapsed'] / pd.Timedelta(minutes=1) # convert to minutes
    
    # create display
    t = (t[['station', 'elapsed', 'id_l', 'id_r']]
         .sort_values(['station', 'id_l', 'id_r']))
    print(t)
    
       station  elapsed  id_l  id_r
    1        a     25.0     1     2
    2        a    -20.0     1     3
    3        a    -20.0     2     1
    5        a    -40.0     2     3
    6        a     25.0     3     1
    7        a     50.0     3     2
    10       b     -5.0     1     2
    11       b     17.0     2     1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-13
      • 2021-10-23
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多