我有一组格式为pandas的日期时间数据集2020-10-02 18:48:21
。我想绘制仅包含针对另一个数据帧的分数值日期时间内的时间。
以下是使用以下代码获得的最接近的代码:
def timePop(oneDate, oneScore, twoDate, twoScore, title):
myFmt = "%H:%M:%S"
for index, value in oneDate.iteritems():
new_time = datetime.fromtimestamp(oneDate[index]).time()
oneDate[index] = datetime.strptime(str(new_time), myFmt)
for index, value in twoDate.iteritems():
new_time2 = datetime.fromtimestamp(twoDate[index]).time()
twoDate[index] = datetime.strptime(str(new_time2), myFmt)
fig, ax = pylt.subplots()
ax.scatter(oneDate, oneScore, c='r', marker='*', label="Popular")
ax.scatter(twoDate, twoScore, c='b', marker='o', label="Unpopular")
pylt.xlabel('24 Hours')
pylt.ylabel('Scores')
pylt.xticks(rotation=45)
# ax.format_xdata = mdates.DateFormatter(myFmt)
# ax.set_xticks([0, 1, 2, 3, 4, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24])
pylt.title('Time and Score Distribution of Posts in %s' % title)
pylt.show()
我已经在StackOverflow以及文档中研究了各种可能的解决方案,但是没有运气。理想情况下,我希望x轴以1小时为增量移动。如果有人可以提供帮助,我将不胜感激。
让我们看看:假设您有一个像这样的玩具示例:
import matplotlib.pyplot as plt
import datetime
dates = [datetime.date(2020,12,i) for i in range(1,24)]
num = [i for i in range(1,24)]
代表圣诞节之前的日子。您只需要提取weekdays
列表中的日期并绘制它们即可:
plt.plot([d.weekday() for d in dates],num,'.') # monday = 0
一周从星期一开始,星期一表示为零。如果要获取带有日期名称的字符串,则可以使用以下命令格式化输出strftime
:
plt.plot([d.strftime("%A") for d in dates],num,'.')
基本上,您可以按字符串对数据进行分组。这也意味着,任何字符串都足够。我们可以将其分类为以下时段:
dates2 = [datetime.datetime(2020,12,i,i,i,0) for i in range(1,24)]
def f(x):
if (x > 4) and (x <= 8):
return 'Early Morning'
elif (x > 8) and (x <= 12 ):
return 'Morning'
elif (x > 12) and (x <= 16):
return'Noon'
elif (x > 16) and (x <= 20) :
return 'Eve'
elif (x > 20) and (x <= 24):
return'Night'
elif (x <= 4):
return'Late Night'
plt.plot([f(d.hour) for d in dates2],num,'.')
首先,我们创建新的伪数据,其类型datetime.datetime
不是而是datetime.date
。然后,我采用了此处建议的类似开关盒结构的功能进行分类。它与以前的过程相同。我们立即创建了一个新列表,该列表.hour
从datetime
对象中提取并将其提供给函数f
,该函数对数据进行分类
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句