【问题标题】:Formatting a pandas datetime object from [HH:MM:ss] to [HH:MM]将 pandas 日期时间对象从 [HH:MM:ss] 格式化为 [HH:MM]
【发布时间】:2018-02-20 15:34:33
【问题描述】:

我有一个pandasDataFrame,它有 4 列(时间、T1、T2、T3),它们各自的值全天使用定制的温度数据记录器获得。 Time 列的格式为 [HH:MM:ss] 但我想将其更改为 [HH:MM] (截断秒数)以进行绘图。有没有一种简单的方法可以实现这一目标?

这是我的代码:(使用 Python 3.6)

import pandas as pd  
import matplotlib.pyplot as plt


df = pd.DataFrame(pd.read_excel('water_data_full_load.xlsx'))  
df.drop("Date", axis = 1, inplace =True)  
df.set_index('Time',inplace =True)  

df.rename_axis({"T1": "Twall", "T2":"Twater", "T3":"Tsurr"}, axis=1, inplace=True)

df['Time'] = df['Time'].apply(lambda x: x[:5])  
graph = df[['Twall','Twater','Tsurr']].plot()  
plt.xticks(rotation =45)  
plt.ylabel('Temperature ($^\circ$C)')  
plt.xlabel('Time of the day (HH:MM)')  
plt.show(graph)

Please refer to this image for the current DataFrame

【问题讨论】:

  • 您要截断秒数还是圆数?例如: 11:34:31 变成 11:34 还是 11:35 ?
  • 答案给我留下了深刻的印象,但看起来他们正在努力解决你缺乏发布的代码、数据或预期结果的问题——任何这些事情都会让你更有可能得到一个有用的答案。
  • 我已经相应地更新了我的问题。

标签: python pandas datetime dataframe


【解决方案1】:

更新:

In [41]: df = pd.DataFrame({'Time': ['11:07:00','12:06:00','13:17:00'], 'Twall':[10,20,30]}).set_index('Time')

In [42]: df
Out[42]:
          Twall
Time
11:07:00     10
12:06:00     20
13:17:00     30

In [43]: df.index = df.index.astype(str).str.rsplit(':',n=1).str[0]

In [44]: df
Out[44]:
       Twall
Time
11:07     10
12:06     20
13:17     30

演示(矢量化方法) - 从datetime dtype 的列中截断秒数:

In [46]: df = pd.DataFrame(pd.date_range('2017-01-01', freq='99S', periods=10), columns=['date'])

In [47]: df
Out[47]:
                 date
0 2017-01-01 00:00:00
1 2017-01-01 00:01:39
2 2017-01-01 00:03:18
3 2017-01-01 00:04:57
4 2017-01-01 00:06:36
5 2017-01-01 00:08:15
6 2017-01-01 00:09:54
7 2017-01-01 00:11:33
8 2017-01-01 00:13:12
9 2017-01-01 00:14:51


In [49]: df['date'] = df['date'].values.astype('<M8[m]')

In [50]: df
Out[50]:
                 date
0 2017-01-01 00:00:00
1 2017-01-01 00:01:00
2 2017-01-01 00:03:00
3 2017-01-01 00:04:00
4 2017-01-01 00:06:00
5 2017-01-01 00:08:00
6 2017-01-01 00:09:00
7 2017-01-01 00:11:00
8 2017-01-01 00:13:00
9 2017-01-01 00:14:00

【讨论】:

  • 使用您更新的代码,我收到此错误:AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')
  • @FrancodeJager,print(df.index.dtype) 的输出是什么?
  • print(df.index.dtype) 的输出为object
  • @FrancodeJager,以及print(df.index[0].dtype)的输出?
  • 我得到以下输出:AttributeError: 'datetime.time' object has no attribute 'dtype'
【解决方案2】:
import pandas as pd

df = pd.DataFrame({ 'Time': ['22:05:00','22:06:00','22:07:00']})

df['Time_to_plot'] = df['Time'].apply(lambda x: x[:5])

print df


       Time Time_to_plot
0  22:05:00        22:05
1  22:06:00        22:06
2  22:07:00        22:07

【讨论】:

  • 感谢您的快速回复。一个问题:我不断收到 KeyError: 'Time' ,我不确定为什么或如何解决它。任何建议将不胜感激。
  • 你真的有一个名为Time的列吗?。
猜你喜欢
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多