LoginSignup
12
10

More than 3 years have passed since last update.

DataFrame ご存知ですか?

DataFrame は Python や R言語でデータを扱ったり、機械学習したいときによく使われるとても便利なライブラリ・オブジェクトです。表形式のデータや2次元の配列のデータを扱うための様々な機能が揃っています。
https://amalog.hateblo.jp/entry/kaggle-pandas-tips

どのくらい便利かというと、Excel や CSV から一気にデータを読み込んだり、2次元配列の任意の行列を抽出したり、表同士を SQL 操作のごとく join したりと、とにかく 2次元データを使う際には欠かせないというレベルです。

でも Java だとこれという DataFrame 相当の実装が無くて、ありがたい DataFrame の恩恵を受けられない、データ処理に時間がかかる、なんで Python じゃないんですかと暴言(?)を吐かれるなどの悲しい目に合うわけです。

Morpheus data science framework

しかし、そこに一筋の光が。
Morpheus data science framework が、その DataFrame と(たぶん)同等の機能を提供してくれています。
https://github.com/zavtech/morpheus-core

A Simple Example に沿って試してみましょう。

Consider a dataset of motor vehicle characteristics accessible here. The code below loads this CSV data into a Morpheus DataFrame, filters the rows to only include those vehicles that have a power to weight ratio > 0.1 (where weight is converted into kilograms), then adds a column to record the relative efficiency between highway and city mileage (MPG), sorts the rows by this newly added column in descending order, and finally records this transformed result to a CSV file.

(このサンプルでは)車の特性データを使用します。CSV を Morpheus DataFrame に読み込み、出力(馬力)重量比が 0.1 を超える条件で行をフィルタし、高速道路/都市部のMPG(燃費?)の比率の列を追加します。追加した列でソートして、結果を CSV ファイルに出力します。

サンプルコードと実行結果

import com.zavtech.morpheus.frame.*;

public class MorpheusTester {

    public static void main(String[] args) {

        DataFrame.read().csv(options -> {
            options.setResource("http://zavtech.com/data/samples/cars93.csv");
            options.setExcludeColumnIndexes(0);
        }).rows().select(row -> {
            double weightKG = row.getDouble("Weight") * 0.453592d;
            double horsepower = row.getDouble("Horsepower");
            return horsepower / weightKG > 0.1d;
        }).cols().add("MPG(Highway/City)", Double.class, v -> {
            double cityMpg = v.row().getDouble("MPG.city");
            double highwayMpg = v.row().getDouble("MPG.highway");
            return highwayMpg / cityMpg;
        }).rows().sort(false, "MPG(Highway/City)").write().csv(options -> {
            options.setFile("./cars93m.csv");
            options.setTitle("DataFrame");
        });

    }
}

戻り値の型が DataFrame 型なので、メソッドチェーンで csv(), select(), add(), sort() と続けて実行できます。csv() のあたりはとても DataFrame 感に溢れています。

  • 処理前のデータ
    image.png

  • 処理後のデータ
    image.png

DataFrame は機能が豊富で、同等かどうか試すのも容易ではありませんが、行抽出、列追加、ソートといった操作を確認することができました。

Java でデータ処理される際には、利用を検討してみても良いと思います。

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10