Create a dataframe with 1 rows and n*m column with an existing dataframe with n rows and m columns

Question:

I have a dataframe and I want to stick the values and create one row with 6 columns. Here is my dataframe.

     time     val1  val2
0   2020-01-01  1   4
1   2020-01-02  2   5
2   2020-01-03  3   6

I want to create the following dataframe:

       val1     val2    val3    val4    val5    val6
0        1      2        3      4       5        6

Here is the code;

import pandas as pd
df = pd.DataFrame()
df['time'] = ['2020-01-01', '2020-01-02', '2020-01-03']
df['val1'] = [1,2,3]
df['val2'] = [4,5,6]
df

I tried to use the pivot, but I got this error; The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Can you help me with that?

Asked By: sadcow

||

Answers:

You could use pd.concat() to get all the values and then create a new df with dynamic column name creation.
Here is an example:

import pandas as pd
df = pd.DataFrame()
df['time'] = ['2020-01-01', '2020-01-02', '2020-01-03']
df['val1'] = [1,2,3]
df['val2'] = [4,5,6]

df2=pd.concat([df["val1"],df["val2"]])
df3=pd.DataFrame()
for value in df2:
    df3[f"val{value}"]=[value]
print(df3)
#output
   val1  val2  val3  val4  val5  val6
0     1     2     3     4     5     6
Answered By: tetris programming

Lets reshape the value columns

c = ['val1', 'val2']
pd.DataFrame(df[c].values.reshape(1, -1, order='F'))

   0  1  2  3  4  5
0  1  2  3  4  5  6
Answered By: Shubham Sharma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.