python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# 创建示例数据框
data = {
'week': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
'city_id': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
'healthy%': [40, 45, 50, 42, 49, 30, 35, 32, 31, 36],
'net%': [10, 12, 9, 11, 15, 13, 14, 10, 8, 9]
}
df = pd.DataFrame(data)
# 对每个城市进行处理
def label_city_data(df):
labels = []
for current_week in range(1, df['week'].max() + 1):
current_data = df[df['week'] == current_week]
if len(current_data) == 0:
continue
current_healthy = current_data['healthy%'].values[0]
current_net = current_data['net%'].values[0]
previous_data = df[df['week'] < current_week]
if len(previous_data) == 0:
labels.append('undefined')
continue
median_healthy = previous_data['healthy%'].median()
median_net = previous_data['net%'].median()
if current_healthy > median_healthy and current_net > median_net:
labels.append('stars')
elif current_healthy > median_healthy and current_net < median_net:
labels.append('risk')
elif current_healthy < median_healthy and current_net > median_net:
labels.append('growing')
elif current_healthy < median_healthy and current_net < median_net:
labels.append('tails')
else:
labels.append('undefined')
return labels
df['label'] = df.groupby('city_id').apply(lambda x: pd.Series(label_city_data(x))).reset_index(level=0, drop=True)
# 为结果数据添加标签
print(df)
# 创建动态变化图
fig, ax = plt.subplots(len(df['city_id'].unique()), 1, figsize=(10, 6 * len(df['city_id'].unique())))
for i, city_id in enumerate(df['city_id'].unique()):
city_data = df[df['city_id'] == city_id]
sns.lineplot(x='week', y='label', data=city_data, ax=ax[i])
ax[i].set_title(f'City {city_id}')
ax[i].set_xticks(city_data['week'])
ax[i].invert_yaxis() # 反转y轴以保持标签顺序
plt.tight_layout()
plt.show()