首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绘制pandas数据帧日期

问绘制pandas数据帧日期
EN

Stack Overflow用户
提问于 2019-09-12 20:09:24
回答 1查看 1.3K关注 0票数 0

我有一个包含27列用电量的pandas数据框,第一列表示两年持续时间的日期和时间,其他列记录了26所房子在两年内的用电量的每小时值。我正在做的是使用k-means进行聚类。当我试图在x轴上绘制日期,在y轴上绘制耗电量的值时,我遇到了一个问题,x和y必须具有相同的大小。我试图重塑,但问题并没有得到解决。

​

代码语言:javascript
复制
import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt
import math
import datetime
data_consumption2 = pd.read_excel(r"C:\Users\user\Desktop\Thesis\Tarek\Parent.xlsx", sheet_name="Consumption")
data_consumption2['Timestamp'] = pd.to_datetime(data_consumption2['Timestamp'], unit='s')
X=data_consumption2.iloc[: , 1:26].values
X=np.nan_to_num(X)
np.concatenate(X)
date=data_consumption2.iloc[: , 0].values
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
y_kmeans = kmeans.predict(X)
C = kmeans.cluster_centers_
plt.scatter(X, R , s=40, c= kmeans.labels_.astype(float), alpha=0.7)
plt.scatter(C[:,0] , C[:,1] , marker='*' , c='r', s=100)

我总是得到相同的错误信息,X和Y必须保存大小,尝试重塑您的数据。当我尝试重塑数据时,它不起作用,因为date列的大小总是小于rest列的大小。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-12 22:51:30

我认为你实际上是在对所有家庭进行时间序列聚类,以找到一段时间内相似的用电量模式。

因此,每个时间戳都成为一个“特征”,而每个家庭的使用情况则成为您的数据行。这将使应用sklearn聚类方法变得更容易,这些方法通常采用method.fit(x)的形式,其中x表示特征(将数据作为具有(row, column)形状的2D数组传递)。因此,您的数据需要进行转置。

重构后的代码如下:

代码语言:javascript
复制
# what you have done 
import pandas as pd
df = pd.read_excel(r"C:\Users\user\Desktop\Thesis\Tarek\Parent.xlsx", sheet_name="Consumption")
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')

# this is to fill all the NaN values with 0
df.fillna(0,inplace=True)

# transpose the dataframe accordingly
df = df.set_index('Timestamp').transpose()
df.rename(columns=lambda x : x.strftime('%D %H:%M:%S'), inplace=True)
df.reset_index(inplace=True)
df.rename(columns={'index':'house_no'}, inplace=True)
df.columns.rename(None, inplace=True)
df.head()

您应该会看到类似这样的内容(不要介意显示的数据,我创建了一些与您的数据类似的虚拟数据)。

​

​

接下来,对于集群,您可以执行以下操作:

代码语言:javascript
复制
from sklearn.cluster import KMeans

kmeans = KMeans(n_clusters=3)
kmeans.fit(df.iloc[:,1:])
y_kmeans = kmeans.predict(df.iloc[:,1:])
C = kmeans.cluster_centers_

# add a new column to your dataframe that contains the predicted clusters
df['cluster'] = y_kmeans

最后,对于绘图,您可以使用以下代码生成您想要的散点图:

代码语言:javascript
复制
import matplotlib.pyplot as plt

color = ['red','green','blue']

plt.figure(figsize=(16,4))

for index, row in df.iterrows():
    plt.scatter(x=row.index[1:-1], y=row.iloc[1:-1], c=color[row.iloc[-1]], marker='x', alpha=0.7, s=40)

for index, cluster_center in enumerate(kmeans.cluster_centers_):
    plt.scatter(x=df.columns[1:-1], y=cluster_center, c=color[index], marker='o', s=100)

plt.xticks(rotation='vertical')
plt.ylabel('Electricity Consumption')
plt.title(f'All Clusters - Scatter', fontsize=20)
plt.show()

​

​

但我建议为单个集群绘制线状图,更具视觉吸引力(对我来说):

代码语言:javascript
复制
plt.figure(figsize=(16,16))

for cluster_index in [0,1,2]:

    plt.subplot(3,1,cluster_index + 1)

    for index, row in df.iterrows():
        if row.iloc[-1] == cluster_index:
            plt.plot(row.iloc[1:-1], c=color[row.iloc[-1]], linestyle='--', marker='x', alpha=0.5)

    plt.plot(kmeans.cluster_centers_[cluster_index], c = color[cluster_index], marker='o', alpha=1)

    plt.xticks(rotation='vertical')
    plt.ylabel('Electricity Consumption')
    plt.title(f'Cluster {cluster_index}', fontsize=20)

plt.tight_layout()
plt.show()

​

​

干杯!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57906413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档