How can I assign rows to columns where the 1st-6th columns are rows 1-6 and the 7th row is loops back to the first column?
How can I assign rows to columns where the 1st-6th columns are rows 1-6 and the 7th row is loops back to the first column?
Suppose we have this data:
data = pd.Series(range(1,8))
Let's assume that these are repeated readings of six sensors, but we are not sure that the measurement cycle is completed. In case of data the cycle has been stopped at the first sensor in the second loop.
Now we want to arrange them in a table with data from each sensor in its own column. I can see two ways to do this. We could use numpy.reshape or DataFrame.pivot.
Here's the first way:
# append enough values to reshape the data
pad = [np.nan]*(6-len(data)%6)
values = np.r_[data.values, pad]
df = pd.DataFrame(values.reshape(-1, 6), columns=[*'123456'])
We might use here numpy.concatenate or pandas.concat as an alternative to numpy.r_. We can't use numpy.resize or ndarray.resize because of how they fill new cells.
Here's the second way I can think of. We create marks of rows and columns of the future table and then build a pivot relying on them:
df = data.to_frame()
df['my_rows'] = df.index // 6
df['my_columns'] = df.index % 6
df.pivot('my_rows', 'my_columns')
Here we could additionaly apply df.reset_index(drop=True) if the original index isn't a sequence 0,1,2,... or we could use pd.RangeIndex(len(df)) instead of df.index in further calculations. Anyway, I hope the main idea is clear enough.