熊猫系列时间,必须转换为日期时间

时间:2018-08-11 00:02:36

标签: python python-3.x pandas

看起来像这样

  time
0   10
1 2321
2  845

我需要将它们转换为日期时间。我已经尝试过

pd.to_datetime(df.Time, format='%H%M')

但是它给出了“时间数据10与格式'%H%M'(匹配)不匹配”

谢谢

预期输出

  time
0 00:10
1 23:21
2 08:45

我需要这些作为日期时间,这样我就可以每小时制造一个垃圾箱。

    time   0  1  2  3  4  5  6  7  8  ... 23
 0  00:10  1
 1  23:21                                  1
 2  08:45                          1  

3 个答案:

答案 0 :(得分:2)

修改后,我相信您需要

     <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
    </dependency>
    <dependency>
     <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
     <version>5.2.3.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
  </dependencies>

答案 1 :(得分:0)

ser = pd.Series([10,2321,845]
print(ser)
0      10
1    2321
2     845
dtype: int64

将整数转换为0预先填充的格式,然后转换为日期时间。

print(pd.to_datetime(ser.apply(lambda x: '{0:0>4}'.format(x)), format='%H%M').dt.strftime("%H:%M"))

0    00:10
1    23:21
2    08:45
dtype: object

答案 2 :(得分:0)

使用zfill

pd.to_datetime(df.time.astype(str).str.zfill(4), format='%H%M').dt.strftime('%H:%M')

0    00:10
1    23:21
2    08:45
Name: time, dtype: object

演示为什么可行:

df.time.astype(str).str.zfill(4)

0    0010
1    2321
2    0845
Name: time, dtype: object

zfill将根据需要用零填充时间,使您可以将日期整整转换为日期时间。

要获得最终所需的输出,可以将Categoricalget_dummies一起使用:

s = pd.to_datetime(df.time.astype(str).str.zfill(4), format='%H%M').dt.strftime('%H:%M')
categories = pd.Categorical(values=s.dt.hour, categories=np.arange(24))

pd.get_dummies(categories)

    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19  20  21  22  23
0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1
2   0   0   0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
相关问题