使用 COVID CSV 进行 K-Means 聚类
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
df = pd.read_csv('Monthly_COVID.csv')
print(df.head())
features = df[['Date', 'COVID-19 Death']]
kmeans = KMeans(n_clusters=3, random_state=42)
df['Cluster'] = kmeans.fit_predict(features)
print(df.head())
plt.figure(figsize=(10, 6))
plt.scatter(df['Date'], df['COVID-19 Death'], c=df['Cluster'], cmap='viridis')
plt.xlabel('Date')
plt.ylabel('COVID-19 Death')
plt.title('K-means Clustering of Monthly COVID Data')
plt.show()
以下代码:
df['集群'] = kmeans.fit_predict(features)
ValueError Traceback(最近一次调用最后一次)
在
我明白了。
更改了 csv 文件的内容,但不起作用。
添加了一些代码以使其变为 dd/mm/yyyy
没成功
尝试将日期列转换为 pandas 日期格式,然后转换为数字格式, K-means 聚类仅支持特征的数值
用它来转换它
# Convert 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
# Convert 'Date' column to numerical timestamp
df['Date'] = pd.to_numeric(df['Date'])