【问题标题】:Pandas: Compare Datetime column on Datetime arrays熊猫:比较日期时间数组上的日期时间列
【发布时间】:2020-10-02 08:09:22
【问题描述】:

我正在学习 Pandas,特别是现在使用 Datetimes。我正在寻找一种按日期时间列选择行的方法。如果 Datetime 列的值在数组 spacexclonx 值之间的范围内。

两个数组:

clonx = array(['2019-08-14T23:32:00.000000000', '2019-08-14T23:35:00.000000000',
       '2019-08-14T23:35:00.000000000', ...,
       '2020-05-24T14:55:00.000000000', '2020-05-24T15:03:00.000000000',
       '2020-05-25T12:09:00.000000000'], dtype='datetime64[ns]')

spacex = array(['2019-08-14T23:27:00.000000000', '2019-08-14T23:30:00.000000000',
   '2019-08-14T23:30:00.000000000', ...,
   '2020-05-24T14:50:00.000000000', '2020-05-24T14:58:00.000000000',
   '2020-05-25T12:04:00.000000000'], dtype='datetime64[ns]')

栏目:

    first['datim']

0      2019-08-14 23:26:00
1      2019-08-14 23:26:00

2      2019-08-14 23:27:00
3      2019-08-14 23:30:00
4      2019-08-14 23:30:00
               ...        
5101   2020-05-25 20:48:00
5102   2020-05-25 20:49:00
5103   2020-05-26 13:52:00
5104   2020-05-26 13:52:00
5105   2020-05-26 14:22:00
Name: datim, Length: 3172, dtype: datetime64[ns]

如何从 first['datim'] 列中获取位于 spacexclonx 日期时间之间的日期时间值?

类似这样的:

start_date = spacex[i]
end_date = clonx[i]
for i in range:
    final = (first['datim'] >= start_date) & (first['datim'] <= end_date)
result final

或者可能使用beween_time,但无法找到使其与数组一起使用的方法。

珍惜你的时间!

【问题讨论】:

  • 您是否需要检查spacexclonx 中的所有值,还是使用.min / .max 就足够了?
  • 感谢您的时间@MrFruppes。它必须在两个数组的值之间,例如:spacex[4] - clonx[4], space[5] - clonx[5],...

标签: python pandas datetime data-science


【解决方案1】:

您可以使用apply 将列添加到您的DataFrame,基于“datim”日期时间与两个日期时间数组的比较。这不能很好地处理大量数据,但对您来说可能没问题。例如,这会告诉您时间是否在日期时间对的any 之间(如@Pygirl 的答案):

def between_any(time):
    for s,c in zip(spacex, clonx):
        if (time  >= s) and (time <= c):
            return True
    return False

df['Between Any'] = df['datim'].apply(between_any)

或者您可以获取值之间的日期对的索引:

def between_index(time):
    output = []
    for i in range(len(spacex)):
        if (time  >= spacex[i]) and (time <= clonx[i]):
            output.append(i)
    return output if output else np.nan

df['Between Indices'] = df['datim'].apply(between_index)

或者您实际上可以获得该值之间的时间戳:

def between_values(time):
    output = []
    for s,c in zip(spacex, clonx):
        if (time  >= s) and (time <= c):
            output.append((s,c))
    return output if output else np.nan

df['Between Values'] = df['datim'].apply(between_values)

根据您的数据,这是这样的:

In[0]: df

Out[0]:
                   datim
0    2019-08-14 23:26:00
1    2019-08-14 23:26:00
2    2019-08-14 23:27:00
3    2019-08-14 23:30:00
4    2019-08-14 23:30:00
5101 2020-05-25 20:48:00
5102 2020-05-25 20:49:00
5103 2020-05-26 13:52:00
5104 2020-05-26 13:52:00
5105 2020-05-26 14:22:00

In[1]:

clonx = pd.Series(['2019-08-14T23:32:00.000000000', '2019-08-14T23:35:00.000000000','2019-08-14T23:35:00.000000000','2020-05-24T14:55:00.000000000', '2020-05-24T15:03:00.000000000','2020-05-25T12:09:00.000000000'])

spacex = pd.Series(['2019-08-14T23:27:00.000000000', '2019-08-14T23:30:00.000000000','2019-08-14T23:30:00.000000000','2020-05-24T14:50:00.000000000', '2020-05-24T14:58:00.000000000','2020-05-25T12:04:00.000000000'])

clonx = pd.to_datetime(clonx)
spacex = pd.to_datetime(spacex)

df['Between Any'] = df['datim'].apply(between_any)
df['Between Indices'] = df['datim'].apply(between_index)
df['Between Values'] = df['datim'].apply(between_values)

df

Out[1]:

                   datim  Between Any Between Indices  \
0    2019-08-14 23:26:00        False             NaN   
1    2019-08-14 23:26:00        False             NaN   
2    2019-08-14 23:27:00         True             [0]   
3    2019-08-14 23:30:00         True       [0, 1, 2]   
4    2019-08-14 23:30:00         True       [0, 1, 2]   
5101 2020-05-25 20:48:00        False             NaN   
5102 2020-05-25 20:49:00        False             NaN   
5103 2020-05-26 13:52:00        False             NaN   
5104 2020-05-26 13:52:00        False             NaN   
5105 2020-05-26 14:22:00        False             NaN   

                                         Between Values  
0                                                   NaN  
1                                                   NaN  
2          [(2019-08-14 23:27:00, 2019-08-14 23:32:00)]  
3     [(2019-08-14 23:27:00, 2019-08-14 23:32:00), (...  
4     [(2019-08-14 23:27:00, 2019-08-14 23:32:00), (...  
5101                                                NaN  
5102                                                NaN  
5103                                                NaN  
5104                                                NaN  
5105                                                NaN  

【讨论】:

  • 非常感谢@Tom(又名黑带熊猫)!我的问题是我必须处理大数据 :( 在 Jupyter 笔记本上测试它需要很长时间......并且没有给出好的结果
  • 试图弄清楚这意味着什么:SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  • @Zaesar 我发布的示例并没有给我这个警告。但是我经常遇到这个问题;它通常意味着(至少)您拥有的其中一行可能没有按照您的想法编辑 DataFrame。查看this article,它对我有帮助
  • 好的,是的!这是工作!!精彩的。很高兴认识你们 :) 祝你们周末愉快!
【解决方案2】:

虽然不是更好的解决方案:

datelist = []
for i in range(len(first.datim)):
    for j in range(len(clonx)):
        if (spacex[j]<=first.datim[i]) and (first.datim[i]<=clonx[j]):
            datelist.append(first.datim[i])
print(set(datelist))

{Timestamp('2019-08-14 23:30:00'), Timestamp('2019-08-14 23:27:00')}

【讨论】:

  • 谢谢!这看起来非常接近我正在寻找的东西!但是当我运行它时,它什么也没显示......另外,我认为先返回['datim'] 会更好。因为它是一行的一列。而且我想得到这个时间范围之间的行......无论如何,对我来说,今天你赢得了一片天堂
  • 可能是你的数据框名称是别的东西。它适用于您提供的少数样本
  • 非常感谢!
猜你喜欢
  • 2021-11-05
  • 2016-07-05
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2017-02-23
  • 2016-09-19
  • 2019-07-19
相关资源
最近更新 更多