Python 日期列和整数列之间的Seaborn热图

Python 日期列和整数列之间的Seaborn热图,python,dataframe,plot,seaborn,heatmap,Python,Dataframe,Plot,Seaborn,Heatmap,我有一个包含'Date'列和'Tweet\u Count'列的数据框 我想画一张热图,显示一个月内每天的推特数量 使用此代码: uk = uk_df.pivot("Date", "Tweet_Count") ax = sns.heatmap(uk) 我得到一个错误: TypeError: '<=' not supported between instances of 'float' and 'str' TypeError:“您要查找的sns.h

我有一个包含
'Date'
列和
'Tweet\u Count'
列的数据框

我想画一张热图,显示一个月内每天的推特数量

使用此代码:

uk = uk_df.pivot("Date", "Tweet_Count")
ax = sns.heatmap(uk)
我得到一个错误:

TypeError: '<=' not supported between instances of 'float' and 'str'

TypeError:“您要查找的
sns.heatmap
所需的数据帧格式是一个透视表,其中包含
索引
分别作为
日期
国家
推特计数
传递到
透视
(如果这导致错误,请升级到最新版本的
pandas
,因为
pivot
在以前的版本中存在问题):

因此,您只需通过
国家/地区
即可实现枢轴:

uk = pd.DataFrame({'Country': {0: 'UK', 1: 'UK', 2: 'UK'},
 'Date': {0: '2020-03-01', 1: '2020-03-02', 2: '2020-03-03'},
 'Tweet_Count': {0: 100, 1: 200, 2: 300}})

uk['Date'] = pd.to_datetime(uk['Date']).dt.date

uk = uk.pivot("Date", "Country", 'Tweet_Count')
ax = sns.heatmap(uk)

向下滚动至第四个代码块:

值得一提的是,您还可以使用以下注释:

ax = sns.heatmap(uk, annot=True, fmt="d")

假设数据如下所示,下面我有两个国家

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

Date = pd.date_range(start='1/3/2020', periods=30,freq="D").strftime('%Y-%m-%d').to_list()
df = pd.DataFrame({'Country':np.repeat(['UK','KU'],len(Date)),
                   'Date':Date*2,
                     'Tweet_Count':np.random.randint(1000,2000,len(Date)*2)})
df.head()

    Country Date    Tweet_Count
0   UK  2020-01-03  1809
1   UK  2020-01-04  1419
2   UK  2020-01-05  1463
3   UK  2020-01-06  1576
4   UK  2020-01-07  1137
如果只有一个国家,那么换位将起作用:

fig, ax = plt.subplots(figsize=(8,2))
uk = df[df['Country']=="UK"]
ax = sns.heatmap(uk[['Date','Tweet_Count']].set_index('Date').T)

如果有2个或更多:

wide_df = df.pivot_table(index="Country",columns="Date",fill_value="Tweet_Count")
wide_df.columns = [j for i,j in wide_df.columns]
fig, ax = plt.subplots(figsize=(8,2))
ax = sns.heatmap(wide_df)

它看起来像是seaborn热图。您可能需要重新考虑如何表示日期数据-例如,x轴是一周中的一天,y轴是周数。这假设您要绘制的国家只有一个。
wide_df = df.pivot_table(index="Country",columns="Date",fill_value="Tweet_Count")
wide_df.columns = [j for i,j in wide_df.columns]
fig, ax = plt.subplots(figsize=(8,2))
ax = sns.heatmap(wide_df)