在python中对数据帧中的值进行聚类

2024-10-03 02:48:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个76列的数据框。第一列包含日期值,其他75列为75个不同钻孔的地下水位。我想根据趋势对钻孔进行聚类(遵循相同模式的钻孔被分组在一起)。如何在python中实现这一点

这是我的数据帧的一个示例

df = pd.DataFrame({
'Date': [1980, 1985, 1990, 1995, 2000],
'borehole1': [53, 43, 33, 22, 18],
'borehole2': [50, 40, 30, 50, 40],
'borehole3': [22, 32, 42, 32, 13],
'borehole4': [60, 65, 82, 72, 60],
'borehole5': [80, 70, 60, 80, 70],
'borehole6': [43, 33, 22, 18, 13]
}) 

df.plot()

因此,在本例中,我将有3个集群:

  • 钻孔1&;钻孔6>&燃气轮机;第一组
  • 钻孔2&;钻孔5>&燃气轮机;第2组
  • 钻孔4及;钻孔3>&燃气轮机;第3组

Tags: 数据gt示例dataframedfdate模式聚类
1条回答
网友
1楼 · 发布于 2024-10-03 02:48:17

K-Means算法非常适合这一点!下面是一个示例。只需将X和y指向特定的数据集,并将“K”设置为3(在本例中已经为您完成)

# K-MEANS CLUSTERING
# Importing Modules
from sklearn import datasets
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# Loading dataset
iris_df = datasets.load_iris()

# Declaring Model
model = KMeans(n_clusters=3)

# Fitting Model
model.fit(iris_df.data)

# Predicitng a single input
predicted_label = model.predict([[7.2, 3.5, 0.8, 1.6]])

# Prediction on the entire data
all_predictions = model.predict(iris_df.data)

# Printing Predictions
print(predicted_label)
print(all_predictions)


# import some data to play with
iris = datasets.load_iris()
X = iris.data[:, :3]  # we only take the first two features.
y = iris.target


fig = plt.figure(figsize=(10,10))
plt = fig.add_subplot(111, projection='3d')
plt.scatter(X[:,0],X[:,1],X[:,2], 
            c=all_predictions, edgecolor='red', s=40, alpha = 0.5)
plt.set_title("First three PCA directions")
plt.set_xlabel("Educational_Degree")
plt.set_ylabel("Gross_Monthly_Salary")
plt.set_zlabel("Claim_Rate")
plt.dist = 10
plt

enter image description here

有关更多信息,请参阅此链接

https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html

相关问题 更多 >