【问题标题】:Extract first 2 digits of a number using python使用python提取数字的前2位
【发布时间】:2018-10-19 13:27:42
【问题描述】:

您好,我有一个 UTC 格式的数字数组。格式是 HH.MM.SS.MS,即小时分钟秒和毫秒。我想将整个数字转换为毫秒。所以我正在提取如下所示的前 2 位数字

hh=int(str(x[1])[:2]) # returns 42 where  hours and minutes mixed

# My data also start with non zero for example x=142826.00
  # doing the same operation like above returns 14( It is perfect). So intention is when 04 extract only 4 and if it is 14 extract 14.


042826.00
042826.25
042826.50
042826.75
042827.00
042827.25
042827.50
042827.75
042828.00
042828.25
042828.50
042828.75
042829.00
042829.25
042829.50
042829.75
042830.00
042830.25
042830.50
042830.75

如何提取并转换为毫秒。

【问题讨论】:

  • 如果它们不是数字,为什么要将它们作为数字?
  • 你得到的是数字而不是文本?
  • @Ignacio Vazquez-Abrams。是的
  • 首先你需要了解你的数据类型,如果你print(type(x))会得到什么?你确定数据在int而不是'str'吗?好像是int,不会有任何前缀0042826.00只会显示为42826.0
  • @hcheung。明白了。它是浮点数,但小时数从 1 位数变为 2 位数格式。即有时 5 小时和 11 小时,具体取决于数据的持续时间。

标签: python-2.7 pandas numpy


【解决方案1】:

我会为自己省去很多麻烦,并使用pandas.to_datetime 已经提供的漂亮格式选项。由于前导零,您的列显然是一个字符串。从那里,很容易得到你想要的任何单位的时间,在这种情况下'ms'

你的字符串格式是'%H%M%S.%f'。我们会将其转换为 datetime 对象,它为您提供开始日期 1900-01-01。我们只需将其减去,然后使用np.timedelta64 将单位转换为毫秒

import pandas as pd
import numpy as np
df
       number
0   042826.00
1   042826.25
2   042826.50
3   042826.75
4   042827.00
5   042827.25
6   042827.50
7   042827.75

(pd.to_datetime(df.number, format='%H%M%S.%f')
 -pd.to_datetime('1900-01-01'))/np.timedelta64(1, 'ms')
#0     16106000.0
#1     16106250.0
#2     16106500.0
#3     16106750.0
#4     16107000.0
#5     16107250.0
#6     16107500.0
#7     16107750.0
#Name: number, dtype: float64

日期1900-01-01 被用作默认值很可能是因为time.strptime 的默认行为

当无法推断出更准确的值时,用于填充任何缺失数据的默认值是 (1900, 1, 1, 0, 0, 0, 0, 1, -1)。字符串和格式都必须是字符串。

【讨论】:

  • @Poka 查看我关于为什么 1900-01-01 是默认时间的编辑。
  • @Poka 除以np.timedelta64(1, 'ms') 是对该时间单位进行单位转换的标准方法,在本例中为ms 请参阅here
  • @Poka 我不确定。上面的数据无论是字符串的数字都有效。在您的整个数据集上,一定有一些错误的条目。如果有很多前导零,想象一个为 000041.12 的字段,当它转换为 41.12pd.to_numeric 时,您将遇到格式错误,因为这与我们提供的指定格式不匹配。在这种情况下,最好在转换之前将它们保留为字符串,因为该数据类型会保留原始格式。
【解决方案2】:

您可能不想在strint 中来回更改它们。 首先使用Decimal/float 得到毫秒,然后使用int 转换其余部分:

numbers = {your array}
milisecond = 0
for number in numbers:
    number = Decimal(number, '.3f')
    millisecond += (number * 1000) % 1000
    number = int(number)
    millisecond += (number % 100) * 1000
    number /= 100
    millisecond += (number % 100) * 60 * 1000
    number /= 100
    millisecond += number * 60 * 60 * 1000

millisecond 是您从数字中获得的毫秒数

【讨论】:

  • 是否可以使用循环一次转换整个数组。
  • 更新我的答案。 milliseconds 将是所有数字的摘要(它会很大,也许你需要使用long 来处理milliseconds
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2014-05-15
相关资源
最近更新 更多