Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading