【问题标题】:numpy.where does not work properly with pandas dataframenumpy.where 不适用于 pandas 数据框
【发布时间】:2018-06-15 06:45:55
【问题描述】:

我正在尝试用 StartTimeEndTime 以及其他内容来划分包含日志数据的巨大日志数据集。 我正在使用 np.where 比较熊猫数据框对象,然后将其划分为 每小时(可能是半小时或每季度) 块,取决于 hrtimeWindow 价值。

下面,在这里,我试图将全天日志分成 1 小时的块,但它没有给我预期的输出。

我完全不知道我的错在哪里!

# Holding very first time in the log data and stripping off 
# second, minutes and microseconds.    
today = datetime.strptime(log_start_time, "%Y-%m-%d %H:%M:%S.%f").replace(second = 0, minute = 0, microsecond = 0)
today_ts = int(time.mktime(today.timetuple())*1e9)
hr = 1
timeWindow = int(hr*60*60*1e9) #hour*minute*second*restdigits

parts = [df.loc[np.where((df["StartTime"] >= (today_ts + (i)*timeWindow)) & \
        (df["StartTime"] < (today_ts + (i+1)*timeWindow)))].dropna(axis= 0, \
         how='any') for i in range(0, rngCounter)]

如果我检查零件数据中的第一个日志条目,则如下所示:

  1. 00:00:00。
  2. 00:43:23。
  3. 01:12:59.
  4. 01:53:55。
  5. 02:23:52。
  6. ....

我希望输出如下所示:

  1. 00:00:00
  2. 01:00:01
  3. 02:00:00
  4. 03:00:00
  5. 04:00:01
  6. ....

虽然我已经使用另一种方式实现了它,但这是一种变通方法,并且由于没有这样的方式,我失去了一些功能。

有人可以弄清楚这种方法到底有什么问题吗?

注意:我正在使用 python notebook 和 pandas,numpy。

【问题讨论】:

  • 能否提供一些示例数据?
  • 我不确定你是否需要 np.where 在这里的.loc。您以什么方式没有得到预期的输出?
  • 另外,直觉上我认为这会更好地通过像pandas.Grouper 这样的时间段来实现,而不是像这样的列表理解。但是我们没有什么可以测试的。请看How to make good reproducible pandas examples

标签: python pandas numpy jupyter-notebook


【解决方案1】:

感谢@raganjosh。

我通过使用pandas Grouper 找到了问题的解决方案。

以下是我的实现。 我为“hr”使用了动态值。

timeWindow = str(hr)+'H'
# Dividing the log into "n" parts. Depends on timewindow initialisation.
df["ST"] = df['StartTime']
df = df.set_index(['ST'])
# Using the copied column as an index.
df.index = pd.to_datetime(df.index)
# Here the parts contain grouped chunks of data as per timewindow, list[0] = key of the group, list[1] = values.
parts = list(df.groupby(pd.TimeGrouper(freq=timeWindow))['StartTime', "ProcessTime", "EndTime"])

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 2017-04-01
    • 2020-05-21
    • 2020-01-11
    • 1970-01-01
    • 2012-11-08
    • 2017-10-29
    • 2022-11-22
    • 2016-02-23
    相关资源
    最近更新 更多