working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,137 snippets matching: flatten

    public by sTiLL-iLL @ SniPitz-KND  181430  1  7  10

    "flatten" your complex arrays

    a flattening Array helper function
    // go flat yerself!
    
    function flatten(arrayToFlatten, rslt) {
        rslt = rslt || [];
        arrayToFlatten.forEach(function(itm) {
            if (Array.isArray(itm)){
                rslt = flatten(itm, rslt);
            }
            else {
                rslt.push(itm);
            }
        });
        return rslt;
    }
    
    // use it...
    
    var someArrayData = [[60, 121, 4, 832],[71, 188, 6, 33]];
    
    // [60, 121, 4, 832, 71, 188, 6, 33]
    
    console.log(flatten(someArrayData));            

    public by lbottaro  7261  40  8  2

    Using Pickle to Save Objects in Python - String Serialization

    You can use the pickle module to save data in a serialized format, typically in a txt string, performing what is better known as data serialization, marshalling, or flattening. Pickle allows you to save an object to a file for later retrieval. Pickling some data will write the python object (dictionary, list, tuple, class) as one long strea
    import pickle 
    
    # The data to save
    myDict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    # The object to pickle
    object_pi = myDict 
    # The file where to write the serialized string
    file_pi = open('filename_pi.obj', 'w')
    # Dump the data as string to file 
    pickle.dump(object_pi, file_pi)
    file_pi.close()

    public by msdn  1815  0  7  0

    FlattenCheckedRows

    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Windows.Forms;
    
    public static string FlattenCheckedRows(this List<DataRow> sender)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (DataRow row in sender)
        {
            sb.AppendLine(string.Join(",", row.ItemArray));
        }
        return sb.ToString();
    }

    public by msdn  1675  0  7  0

    StringifyProperty: This function takes a string or vector string property value and returns a flattened string representation of it.

    This function takes a string or vector string property value and returns a flattened string representation of it.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    /// <summary>
    /// This function takes a string or vector string property value and returns a flattened string representation of it.
    /// </summary>
    public static string StringifyProperty(object property)
    {
        string propertyString = "";
        if (property != null)
        {
            var vectorProperty = property as IEnumerable<string>;
            if (vectorProperty != null)
            {
                foreach (var prop in vectorProperty)
                {
                    propertyString += prop + "; ";
                }
            }
            else
            {
                propertyString = property.ToString();
            }
        }
        return propertyString;
    }

    external by tjvc  1490807  455  4  0

    Flatten JSON and output as CSV

    Flatten JSON and output as CSV: json2csv.py
    # coding: utf-8
    
    #
    # Flatten JSON and output as CSV
    #
    # Invoke with the path to the JSON file as an argument, e.g.
    #
    #   python json2csv.py data.json
    #
    # Outputs to a CSV file in the working directory
    #
    # JSON flattening function from: http://goo.gl/z0mzsH
    #
    
    from collections import OrderedDict
    import csv
    import json
    import sys
    
    infile = sys.argv[1]
    outfile = open("output.csv", "w")
    
    writer = csv.writer(outfile, delimiter=",")
    
    data = json.load(open(infile), object_pairs_hook=OrderedDict)
    
    # Recursively flatten JSON
    def flatten(structure, key="", path="", flattened=None): 
        if flattened is None:
            flattened = OrderedDict()    
        if type(structure) not in(OrderedDict, list):
            flattened[((path + "_") if path else "") + key] = structure    
        elif isinstance(structure, list):
            for i, item in enumerate(structure):
                flatten(item, "", path + "_" + key, flattened)    
        else:
            for new_key, value in structure.items():
                flatten(value, new_key, path + "_" + key, flattened)    
        return flattened
    
    # Write fields
    fields = []
    for result in data["results"]:
        flattened = flatten(data["results"][0])
        for k, v in flattened.iteritems():
            if k not in fields:
                fields.append(k)
    writer.writerow(fields)
    
    # Write values
    for result in data["results"]:
        flattened = flatten(result)
        row = []
        for field in fields:
            if field in flattened.iterkeys():
                row.append(flattened[field])
            else:
                row.append("")
        writer.writerow(row)
    
    

    external by rafaan  24603  281  4  0

    Convert Nested JSON to Pandas DataFrame and Flatten List in a Column

    Convert Nested JSON to Pandas DataFrame and Flatten List in a Column: gistfile1.py
    import json
    from pandas.io.json import json_normalize
    import pandas as pd
    
    with open('C:\filename.json') as f:
        data = json.load(f)
    
    df = pd.DataFrame(data)   
    
    normalized_df = json_normalize(df['nested_json_object'])
    
    '''column is a string of the column's name.
    for each value of the column's element (which might be a list),
    duplicate the rest of columns at the corresponding row with the (each) value.
    '''
    
    def flattenColumn(input, column):
        column_flat = pd.DataFrame([[i, c_flattened] for i, y in input[column].apply(list).iteritems() for c_flattened in y], columns=['I', column])
        column_flat = column_flat.set_index('I')
        return input.drop(column, 1).merge(column_flat, left_index=True, right_index=True)
        
    new_df = flattenColumn(normalized_df, 'column_name')
    
    

    external by hgupta  286  0  3  0

    Pure JavaScript (JS) Array Flatten method (like Ruby Array#flatten)

    Pure JavaScript (JS) Array Flatten method (like Ruby Array#flatten): js_array_flatten.js
    Array.prototype.flatten = function(limit) {
      var level = 0;
      if(limit === undefined) limit = Number.POSITIVE_INFINITY;
      if(arguments.length > 1) level = arguments[1];
    
      return this.reduce(function(a, b) {
        if((b instanceof Array) && level < limit)
          a = a.concat(b.flatten(limit, level + 1));
        else
          a.push(b);
        return a;
      }, []);
    };
    
    console.log([1, 2, 3].flatten()); // => [1, 2, 3]
    console.log([[1], 2, 3].flatten()); // => [1, 2, 3]
    console.log([[1], 2, 3].flatten(1)); // => [1, 2, 3]
    console.log([[[1]], 2, 3].flatten(1)); // => [[1], 2, 3]
    console.log([[[[[1]],2]],3].flatten(1)); // => [[[[1]], 2], 3]
    console.log([[[[[1]],2]],3].flatten(2)); // => [[[1]], 2, 3]
    console.log([[[[[1]],2]],3].flatten(3)); // => [[1], 2, 3]
    
    

    external by Bruno Barreto  34422  0  3  0

    Some Clojure parsing and flatten

    Some Clojure parsing and flatten: new_file0.clj
    (defn parse-data
      [form-data]
      (->> (map (fn [[k v]] [k (:value v)]))
           (into {})))
    
    (defn flatten-keys* [a ks m]
      (if (map? m)
        (reduce into (map (fn [[k v]] (flatten-keys* a (conj ks k) v)) (seq m)))
        (assoc a ks m)))
    
    (defn flatten-keys [m] (flatten-keys* {} [] m))
    
    (defn flatten-data
      [form-data]
      (reduce
        (fn [result kv]
          (if (= :value (last (first kv)))
            (let [nest-level (count (first kv))]
              (conj result {(nth (first kv) (- nest-level 2)) (last kv)}))
            result
            ))
        {}
        (flatten-keys form-data))
    )
    
    

    external by Chris Carrick  80  0  1  0

    multi-dimensional array flatten function I came up with messing around after I got stumped on a test question re: flattening multi-dimensional arrays.

    multi-dimensional array flatten function I came up with messing around after I got stumped on a test question re: flattening multi-dimensional arrays.: flatten().js
    function flatten (arr) {
      // create a 'static' variable array to hold the output 
      // (actually a property of the function since functions are objects in JS)
      // this is pretty clever and not my idea but
      flatten.output = flatten.output || [];
      // loop over array
      for (var i = 0; i < arr.length; i++) {
        // if arr[i] is itself an array
        if (arr[i] instanceof Array) {
          // call flatten passing in arr[i] in order to flatten that
          flatten(arr[i]);
        // otherwise
        } else {
          // push arr[i] onto flatten.output array
          flatten.output.push(arr[i]);
        }
      }
      // return flatten.output array
      return flatten.output;
    }
    
    var test = [1,2,3,[4,5,[6,7,[8,[9,10]]]],'one','two',['dog',5,['cat','bird']],[{key: 'value'},[{key: 'value', key2: 'value2', foo: function () {return 'bar';}, nest: {nest: 'nested'}, nestArr: ['whoa','man']}]]];
    
    flatten(test);
    /*
      [ 1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        'one',
        'two',
        'dog',
        5,
        'cat',
        'bird',
        { key: 'value' },
        { key: 'value',
          key2: 'value2',
          foo: [Function],
          nest: { nest: 'nested' },
          nestArr: [ 'whoa', 'man' ] } ]
      */
    
    

    external by Ed de Almeida  45  0  1  0

    Flatten an array without using Array#flatten

    Flatten an array without using Array#flatten: flatten.rb
    def ints_only?(arr)
      res = true
      arr.map { |item| res = res && item.is_a?(Integer) ? true : false }
      res
    end
    
    def array_flatten(arr)
      while !ints_only?(arr) do
        new_arr = Array.new
        arr.map{ |item|
          if item.is_a?(Integer) then
            new_arr.push(item)
          else 
            item.map{ |sitem| new_arr.push(sitem) }
          end
          arr = new_arr
        }
      end
      arr
    end
    
    
    
    • Public Snippets
    • Channels Snippets