Transpose Rows and Columns

I have something that could be massaged into what you need. The follow code is designed to take one or more datasets, each with a just a few rows, and flip all the rows into columns. Should be close to what you need:


#----------
# Construct a dataset with columns from supplied datasets rows.  The column
# names from the first dataset become the string values in the first column
# of the result.  The first argument to the function is a sequence of names
# for the dataset arguments.  The name string is used verbatim if the
# dataset has one row.  Otherwise it is concatenated with the row number.
def flipData(names, *args):
	from com.inductiveautomation.ignition.common.util import DatasetBuilder
	from java.lang import String as jString, Object as jObject, Long as jLong
	ds1 = args[0]
	firstcolumn = [x for x in ds1.columnNames]
	types = [jString]
	heads = ['_']
	columns = [firstcolumn]
	for dsn, ds in enumerate(args):
		collist = range(ds.columnCount)
		if ds.rowCount==0:
			heads.append(names[dsn])
			types.append(jObject)
			columns.append([None for x in firstcolumn])
		for rn in range(ds.rowCount):
			if rn==0:
				heads.append(names[dsn])
			else:
				heads.append("%s %d" % (names[dsn], 1+rn))
			types.append(jObject)
			row = [ds.getValueAt(rn, cn) for cn in collist]
			for i, x in enumerate(row):
				if isinstance(x, long):
					row[i] = jLong(x)
			columns.append(row)
	rows = zip(*tuple(columns))
	builder = DatasetBuilder.newBuilder().colNames(heads).colTypes(types)
	for row in rows:
		t = tuple(row)
		builder.addRow(*t)
	return builder.build()
3 Likes