python - 错误值Error : cannot reindex from a duplicate axis because of concatenating dataframes

标签 python csv scikit-learn

我在我的项目中实现了实验环境。

该组件基于 Scikit learn。

在此组件中,我将给定的 CSV 读入 pandas 数据帧。 之后,我选择了最佳特征并将给定数据帧的维度从 100 减少到 5。 之后,我将删除的 ID 列添加到这个简化的数据框中以供将来使用。该列在降维过程中被删除。

一切正常,直到我更改代码以读取所有 CSV 文件并返回一个联合数据帧:

请看下面的代码: 读取所有 CSV:

dataframes = []

from os import listdir
from os.path import isfile, join
files_names = [f for f in listdir(full_path_directory_files) if   isfile(join(full_path_directory_files, f))]
for file_name in files_names:
    full_path_file = full_path_directory_files + file_name

    data_frame = pd.read_csv(full_path_file, index_col=None, compression="infer")
dataframes.append(dataframe)

之后我在数据帧之间进行了串联

features_dataframe = pd.concat(dataframes, axis=0)

我也查了一下。 我创建了两个不同的数据框,形状 = (200, 100) 连接后变成 (400, 100)

之后数据帧被发送到以下方法:

 def _reduce_dimensions_by_num_of_features(self, features_dataframe, truth_dataframe, num_of_features):
    print("Create dataframe with the {0} best features".format(num_of_features))

## In those functions I got the ids and their class

    ids, id_series = self._create_ids_by_dataframe(features_dataframe)
    features_dataframe_truth_class = self._extract_truth_class_by_truth_dataframe(truth_dataframe, ids)


    k_best_classifier = SelectKBest(score_func=f_classif, k=num_of_features)
    k_best_features = k_best_classifier.fit_transform(features_dataframe, features_dataframe_truth_class)

    reduced_dataframe_column_names = self._get_k_best_feature_names(k_best_classifier, features_dataframe)


    reduced_dataframe = pd.DataFrame(k_best_features, columns=reduced_dataframe_column_names)

现在我检索了 ID 列:

    reduced_dataframe["Id"] = id_series

软件在消息上失败:

ValueError: cannot reindex from a duplicate axis

这仅在数据帧连接之后发生。

如何将 ID 列添加到数据框中而不出现错误?

最佳答案

我发现了问题:

连接数据帧后,索引发生更改,当我们添加行时:

reduced_dataframe["Id"] = id_series

我们遇到错误。

解决方案是重置索引:

features_dataframe = pd.concat(dataframes, axis=0)
features_dataframe.reset_index(drop=True, inplace=True)

关于python - 错误值Error : cannot reindex from a duplicate axis because of concatenating dataframes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975957/

相关文章:

Python,运行终端,并在其中执行命令

python - 将 CPP exe 打印成 Python 脚本输入

c# - 将 csv 格式的 .txt 文件作为工作表添加到 C# 中的现有工作簿

python - 从 CSV 表创建 User-PageView 矩阵

python - 多项式朴素贝叶斯参数 alpha 设置? scikit学习

python - 大矩阵对角化python

python - Xml 文件到 Csv 的文件夹

php - 将文件导入到 Mysql 数据库并使用 PATHINFO_EXTENSION

python - 通过单行字典用决策树模型进行预测

Python RandomForest - 未知标签错误