[Python] 纯文本查看 复制代码 import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
file_path = 'D:\\py001\\中美关系.xlsx'
df = pd.read_excel(file_path, sheet_name=0)
df.columns = ['Year'] + [f'{i}月' for i in range(1, 13)]
df['Year'] = df['Year'].astype(int)
for col in df.columns[1:]:
df[col] = pd.to_numeric(df[col], errors='coerce').astype(float)
df.set_index('Year', inplace=True)
df.fillna(method='ffill', inplace=True)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
decade_avg = pd.DataFrame()
for start_year in range(1950, df.index.max() + 1, 10):
end_year = start_year + 9
decade_df = df[(df.index >= start_year) & (df.index <= min(end_year, df.index.max()))]
month_avg = decade_df.mean(axis=0)
decade_avg[f'{start_year}-{end_year}'] = month_avg.round(2)
decade_avg = decade_avg.T
plt.figure(figsize=(10, 8))
plt.title('中美关系每十年月平均值热力图')
plt.xlabel('月份')
plt.ylabel('十年')
plt.xticks(rotation=45)
sns.heatmap(decade_avg, annot=True, fmt=".2f", cmap="coolwarm", cbar_kws={'orientation': 'horizontal', 'shrink': 0.58, 'pad': 0.08})
plt.show() |