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

Question:

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?

Asked By: Ashi

||

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 ‘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
Answered By: mozway
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.