Builds a csv string.

  Args:
    data_dict: dict of {column_name: 1 value}
    column_names: list of column names

  Returns:
    A csv string version of data_dict
326548
def encode_csv(data_dict, column_names):
  
  import csv
  import six
  values = [str(data_dict[x]) for x in column_names]
  str_buff = six.StringIO()
  writer = csv.writer(str_buff, lineterminator='')
  writer.writerow(values)
  return str_buff.getvalue()
1302135
def dict_row_strategy(column_names):
    
    # replace empty column names with indices
    column_names = [(name or idx) for idx, name in enumerate(column_names)]

    def row_factory(row):
        return dict(zip(column_names, row))

    return row_factory
1030734
def _get_csv_from_columns(table, filename, csvs):
    
    csvs[filename] = OrderedDict()
    try:
        if "columns" in table:
            try:
                for _name, _column in table["columns"].items():
                    csvs[filename][_name] = {"number": _column["number"], "values": _column["values"]}
            except KeyError as ke:
                print("Error: get_csv_from_columns: {}, {}".format(filename, ke))
            except Exception as e:
                print("Error: get_csv_from_columns: inner: {}, {}".format(filename, e))
                logger_csvs.error("get_csv_from_columns: inner: {}, {}".format(filename, e))
    except Exception as e:
        print("Error: get_csv_from_columns: {}, {}".format(filename, e))
        logger_csvs.error("get_csv_from_columns: {}, {}".format(filename, e))

    return csvs
605609
def _dict_to_name_value(data):
    '''
    
    '''
    if isinstance(data, dict):
        sorted_data = sorted(data.items(), key=lambda s: s[0])
        result = []
        for name, value in sorted_data:
            if isinstance(value, dict):
                result.append({name: _dict_to_name_value(value)})
            else:
                result.append({name: value})
    else:
        result = data
    return result
163241
def make_dict(self, field_values):
        ''' 
        '''
        data_dict = {}
        for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters):
            try:
                # We have to deal with the '-' based on the field_type
                data_dict[key] = self.dash_mapper.get(field_type, '-') if value == '-' else converter(value)
            except ValueError as exc:
                print('Conversion Issue for key:{:s} value:{:s}\n{:s}'.format(key, str(value), str(exc)))
                data_dict[key] = value
                if self._strict:
                    raise exc

        return data_dict
1035198
def keys_to_string(data):
    
    if isinstance(data, dict):
        for key in list(data.keys()):
            if isinstance(key, six.string_types):
                value = data[key]
                val = keys_to_string(value)
                del data[key]
                data[key.encode("utf8", "ignore")] = val
    return data
977653
def columns_dataset(self):
        
        data = {}
        words_total = {}

        for instance, words in self.raw_dataset.items():
            words_item_total = {}
            for word in words:
                words_total.setdefault(word, 0)
                words_item_total.setdefault(word, 0)
                words_total[word] += 1
                words_item_total[word] += 1
            data[instance] = words_item_total

        columns = sorted(words_total.keys(),
                         key=lambda w: words_total[w],
                         reverse=True)[:250]
        columns = sorted(columns)
        dataset = {}
        for instance in data.keys():
            dataset[instance] = [data[instance].get(word, 0)
                                 for word in columns]
        return columns, dataset
358374
def _description_columns_json(self, cols=None):
        
        ret = {}
        cols = cols or []
        d = {k: v for (k, v) in self.description_columns.items() if k in cols}
        for key, value in d.items():
            ret[key] = as_unicode(_(value).encode("UTF-8"))
        return ret
602491
def _load_text_csv_file(self, filename, separator=',', **kwargs):
        """"""
        rdd_input = self.sc.textFile(filename)

        def load_csv_record(line):
            input_stream = StringIO.StringIO(line)
            reader = csv.reader(input_stream, delimiter=',')
            # key in first column, remaining columns 1..n become dict key values
            payload = reader.next()
            key = payload[0]
            rest = payload[1:]
            # generate dict of "1": first value, "2": second value, ...
            d = {}
            for (cell,i) in izip(rest, range(1,1+len(rest))):
                d[str(i)] = cell
            # just in case, add "0": key
            d["0"] = key
            return (key, d)

        rdd_parsed = rdd_input.map(load_csv_record)
        return rdd_parsed
13981
def read_csv(fname):
    
    values = defaultdict(list)
    with open(fname) as f:
        reader = csv.DictReader(f)
        for row in reader:
            for (k,v) in row.items():
                values[k].append(v)
    npvalues = {k: np.array(values[k]) for k in values.keys()}
    for k in npvalues.keys():
        for datatype in [np.int, np.float]:
            try:
                npvalues[k][:1].astype(datatype)
                npvalues[k] = npvalues[k].astype(datatype)
                break
            except:
                pass
    dao = DataAccessObject(npvalues)
    return dao
147771
def categorize(
    data, col_name: str = None, new_col_name: str = None,
    categories: dict = None, max_categories: float = 0.15
):
    

    _categories = {}
    if col_name is None:
        if categories is not None:
            raise Exception(
                'col_name is None when categories was defined.'
            )
        # create a list of cols with all object columns
        cols = [
            k for k in data.keys()
            if data[k].dtype == 'object' and
            (data[k].unique() / data[k].count()) <= max_categories
        ]
    else:
        # create a list with col_name
        if new_col_name is not None:
            data[new_col_name] = data[col_name]
            col_name = new_col_name

        cols = [col_name]

    for c in cols:
        if categories is not None:
            # assert all keys is a number
            assert all(type(k) in (int, float) for k in categories.keys())
            # replace values using given categories dict
            data[c].replace(categories, inplace=True)
            # change column to categorical type
            data[c] = data[c].astype('category')
            # update categories information
            _categories.update({c: categories})
        else:
            # change column to categorical type
            data[c] = data[c].astype('category')
            # change column to categorical type
            _categories.update({
                c: dict(enumerate(
                    data[c].cat.categories,
                ))
            })
    return _categories
803700
def serialize(dictionary):
    

    data = []
    for key, value in dictionary.items():
        data.append('{0}="{1}"'.format(key, value))
    return ', '.join(data)
951474
def to_csv(columns: nil)
      attributes = members
      attributes = columns & attributes if columns

      row = attributes.map! { |column| to_csv_value(column) }

      ::CSV.generate_line(row)
    end
723574
def col_append(self, col_key, value_list):
        
        if col_key in self._col_keys:
            raise KeyError('Key %s already exists col keys.' % col_key)
        if not isinstance(value_list, (tuple, list)):
            value_list = [value_list] * len(self._row_keys)
        if not len(value_list) == len(self._row_keys):
            raise ValueError('Length of data to set does not meet expected col length of %i' % len(self._row_keys))
        self._col_keys.append(col_key)
        for r, v in zip(self._row_keys, value_list):
            self[r, col_key] = v
427681
def data_from_dict(self, data):
        

        nvars = []
        for key, val in data.items():
            self.__dict__[key].extend(val)

            # assure the same parameter matrix size
            if len(nvars) > 1 and len(val) != nvars[-1]:
                raise IndexError(
                    'Model <{}> parameter <{}> must have the same length'.
                    format(self._name, key))
            nvars.append(len(val))

        # assign idx-uid mapping
        for i, idx in zip(range(self.n), self.idx):
            self.uid[idx] = i
1103271
def load_csv_data(resource_name):
    # type: (str) -> List[str]
    
    data_bytes = pkgutil.get_data('clkhash', 'data/{}'.format(resource_name))
    if data_bytes is None:
        raise ValueError("No data resource found with name {}".format(resource_name))
    else:
        data = data_bytes.decode('utf8')
        reader = csv.reader(data.splitlines())
        next(reader, None)  # skip the headers
        return [row[0] for row in reader]
1052561
def csv_format(csv_data, c_headers=None, r_headers=None, rows=None, **kwargs):
    
    result = None
    c_headers = [] if c_headers is None else c_headers
    r_headers = [] if r_headers is None else r_headers
    rows = [] if rows is None else rows

    result_format = kwargs.get('result_format', ARRAY_RAW_FORMAT)

    # DICT FORMAT
    if result_format == DICT_FORMAT:
        result = csv_dict_format(csv_data, c_headers, r_headers)

    # ARRAY_RAW_FORMAT
    elif result_format == ARRAY_RAW_FORMAT:
        result = rows

    # ARRAY_CLEAN_FORMAT
    elif result_format == ARRAY_CLEAN_FORMAT:
        result = csv_array_clean_format(csv_data, c_headers, r_headers)

    else:
        result = None

    # DEFAULT
    if result and result_format < DICT_FORMAT:
        result = [result]

    return result