【问题标题】:exporting dataframe to arff file python将数据框导出到arff文件python
【发布时间】:2018-08-06 05:29:50
【问题描述】:

我正在尝试将 pandas 数据框导出到 .arff 文件以在 Weka 中使用它。我已经看到模块liac-arff 可用于此目的。继续文档here 看来我必须使用 arff.dump(obj,fp) 虽然,我正在为 obj (一本字典)而苦苦挣扎,我猜我必须自己创建它。你建议我如何正确地做到这一点?在一个大数据集(3 000 000 行和 95 列)中,您是否可以提供使用 python(v 2.7)从 pandas 数据帧导出到 .arff 文件的任何示例?

【问题讨论】:

    标签: python arff


    【解决方案1】:

    首先安装包: $ pip install arff

    然后在 Python 中使用:

    import arff
    arff.dump('filename.arff'
          , df.values
          , relation='relation name'
          , names=df.columns)
    

    其中df 的类型为pandas.DataFrame。瞧。

    【讨论】:

      【解决方案2】:

      这就是我最近使用 liac-arff 包的方式。事件如果 arff 包更容易使用,它不允许定义列类型和分类属性的值。

      df = pd.DataFrame(...)
      attributes = [(c, 'NUMERIC') for c in df.columns.values[:-1]]
      attributes += [('target', df[t].unique().astype(str).tolist())]
      t = df.columns[-1]
      data = [df.loc[i].values[:-1].tolist() + [df[t].loc[i]] for i in range(df.shape[0])]
      
      arff_dic = {
          'attributes': attributes,
          'data': data,
          'relation': 'myRel',
          'description': ''
      }
      
      with open("myfile.arff", "w", encoding="utf8") as f:
           arff.dump(arff_dic, f)
      

      target 等分类属性的值必须是 str 类型,如果是数字则为 event。

      【讨论】:

        【解决方案3】:

        受@M 回答的启发。富兰克林虽然效果不佳,但想法就在那里。

        import arff
        
        input // your DataFrame.
        attributes = [(j, 'NUMERIC') if input[j].dtypes in ['int64', 'float64'] else (j, input[j].unique().astype(str).tolist()) for j in input]
        
        
        arff_dic = {
          'attributes': attributes,
          'data': input.values,
          'relation': 'myRel',
          'description': ''
        }
        
        
        with open("myfile.arff", "w", encoding="utf8") as f:
          arff.dump(arff_dic, f)
        

        按照上面的这个 sn-p,它会输出一个具有所需正确格式的 arff 文件。祝大家好运!

        【讨论】:

          猜你喜欢
          • 2020-09-05
          • 1970-01-01
          • 2018-12-18
          • 2018-09-23
          • 2014-12-17
          • 2015-09-03
          • 2020-06-04
          • 2016-12-01
          相关资源
          最近更新 更多