【问题标题】:Using a timestamp array to find elements on an array and a dataframe使用时间戳数组查找数组和数据帧上的元素
【发布时间】:2021-09-23 19:56:55
【问题描述】:

我有 2 个数组和一个 pandas 数据框。我想要完成的是: 使用具有 datetime64 值的一个数组、一个 3 个展平的 3D 数组(与时间相同的长度)和一个 pandas 数据帧(超过 6000 行)

我需要做的是: 使用时间数组上的时间戳,搜索数据框中匹配的时间戳,并使用这些值创建两个新数组(新时间和新 DF) 此外,展平数组的值与时间数组相同,所以我想将它们提取到一个新数组(new_flat)

一些sn-ps代码:

mini_time = ['2015-03-25T13:05:00.000000Z',
'2015-03-25T13:05:03.000000Z',
 '2015-03-25T13:05:06.000000Z',
 '2015-03-25T13:05:09.000000Z',
 '2015-03-25T13:05:12.000000Z']

mini_flat=np.zeros((5,5,3750))

np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(5, 40)),
                  columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMN'),
                  index=['2015-03-25T13:05:00.000000{}'.format(i) for i in range(5)])

我知道这里的索引是一个字符串,但是在我原来的 dtaframe 中,有一个名为“日期”的列,其中包含我制作成索引的一系列 6000 多个时间戳

这是我目前所拥有的:

df=df.set_index('Date')

这允许我将 DF 上的时间戳设置为索引

new_Time = []
new_Flat = []
new_DF = []
for t in range(len(time)):
    s = df.loc[df.index.unique()[df.index.unique().get_loc(np.datetime64(time[mini_time]), method='nearest')]]
    if (s.index - np.datetime64(time[mini_time])) < 0.2: #check this by hand 
        new_Time.append(time[mini_time])
        new_DF.append(s)
        new_Flat.mini_flat[mini_time]
        
  UFuncTypeError: ufunc 'subtract' cannot use operands with types dtype('O') and dtype('<M8[us]')

如果我将 s.index 更改为 s.name,

TypeError: Cannot compare type Timedelta with type float

我至少得到了正确的方法吗?

【问题讨论】:

  • 请始终包含最少的示例数据。 How to make good reproducible pandas examples
  • 认为我添加了我正在使用的较小规模
  • 您的示例代码为df=df.set_index('Date') 行生成KeyError: "None of ['Date'] are in the columns"。请阅读并提供minimal reproducible example。 - 如果列表或系列应该是字符串以外的对象,请确保示例数据反映了这一点。请阅读How to Ask

标签: python arrays pandas machine-learning


【解决方案1】:

在多次尝试失败后修复 错误是 IF 运算在减去两次后所做的比较。 使用 s.index 给出了 df 的列名,而 s.name 给出了时间戳 使用 s.name - time[t],它会产生一个 TimeDelta,它不能根据浮点数进行检查,但是 .total_seconds 方法(因为时间戳都相隔 3 秒,所以检查一个足够小的数字)做了诡计

唯一的改变必须在 if 循环中完成:

if ((s.name - np.datetime64(time[t])).total_seconds()) < 0.2: 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多