【问题标题】:Save in Excel error - 'list' object has no attribute 'to_excel'保存在 Excel 中错误 - 'list' 对象没有属性 'to_excel'
【发布时间】:2021-05-21 22:14:43
【问题描述】:

我试图将结果保存在 excel 中,但出现错误 - 'list' 对象没有属性 'to_excel'。 除了最后一行(保存结果)之外,我运行整个代码都没有问题。

你能帮我找出错误吗?谢谢

from collections import Counter
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

from sklearn.cluster import KMeans 
from sklearn.preprocessing import StandardScaler
from scipy.spatial import distance

df1=pd.read_csv("Clus_readinFile.csv", index_col="Site_ID")
df1.head(5)

# Standardization (z-score)
scaler = StandardScaler()
df_std = scaler.fit_transform(df1)
df_std

centroids_All = []
for cluster in range(1,15):
    kmeans = KMeans(n_jobs = -1, n_clusters = cluster, init='k-means++')
    kmeans.fit(df_std)
    counts = dict(Counter(kmeans.labels_))
    counts = pd.DataFrame.from_dict(counts, orient='index',  columns=['Stores'])
    centroids_deno = pd.DataFrame(scaler.inverse_transform(kmeans.cluster_centers_),columns= df1.columns)
    centroids_deno['Stores'] = counts['Stores']
    centroids_All.append(centroids_deno)

centroids_All.to_excel("centroidsAllResult.xlsx")

【问题讨论】:

  • centroids_All 是一个列表。列表没有 to_excel() 函数。你真正想保存到excel什么?它应该是一个数据框
  • 嗨,Pranav,是的,我想将其保存为数据框。我觉得我已经通过 pd.DataFrame 将其转换为数据框。我需要如何更改它?谢谢
  • centroids_deno 是您的数据框。你在centroids_All上做to_excel()。
  • 另外,请修正代码的缩进。 for 循环的内容必须缩进。请参阅formatting help 以获取有关如何使用代码围栏正确格式化代码的帮助。

标签: python dataframe k-means


【解决方案1】:

to_excel() 函数定义在 pandas 对象下,可以被 pandas DataFrame 对象调用。但是,您要调用to_excel() 函数的对象centroids_All 被定义为列表。尽管您将 pandas Dataframe 附加到列表 centroids_All 中,但它本身仍然不是 pandas DataFrame。因此出现错误。

您可以使用Dataframe.append() 在循环中追加/连接生成的DataFrame,而不是使用列表追加。然后使用生成的DataFrame对象调用to_excel()

只需将您的代码centroids_All = [] 更改为:

centroids_All = pd.DataFrame()

这是为了创建一个空的 pandas DataFrame 而不是空列表。

附加 DataFrame 的代码只需要稍作改动(幸运的是,语法与附加列表的代码相似)。 ignore_index=True 被添加到 append() 调用中,以便重新序列化索引。结果代码是:

centroids_All = centroids_All.append(centroids_deno, ignore_index=True)

注意将附加的结果重新分配回合并数据框。

【讨论】:

  • 嗨,Seabean,我明白你的意思了。如果我想在 cluster =1, 2, 3,....,15 时追加并保存结果,我需要如何更改它?谢谢
  • 使用 pd.concat。请参阅文档here
  • @Qianru Song,也可以参考DataFrame.append()函数。文档here
  • @QianruSong 希望你已经解决了你的问题。我进一步编辑了建议的代码以对其进行微调(基于我之前所做的工作)。
猜你喜欢
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
相关资源
最近更新 更多