Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a single-column from a pandas data frame with n columns

I have a data frame with 3 columns: A, B and C as below:

A: 1 2 3

B: 10 20 30

C: 100 200 300

I need to save the values only in a csv file in "one" row like this ( no need to save the column name)

1 2 3 10 20 30 100 200 300

I tried to create a new data frame with only one coumn using pandas, and transpose it, then write it to a csv file. But I couln't figure out how. Could you please help me?

like image 774
Ashi Avatar asked Sep 16 '25 22:09

Ashi


1 Answers

You can use unstack, to_frame and T:

(df.unstack().to_frame().T
   .to_csv('out.csv', header=None, index=None, sep=' ')
)

Or, with help of numpy's ravel:

(pd.DataFrame([df.to_numpy().ravel('F')])
   .to_csv('out.csv', header=None, index=None, sep=' ')
)

Output file:

1 2 3 10 20 30 100 200 300
like image 145
mozway Avatar answered Sep 19 '25 12:09

mozway