Home > Software design >  How to save a column of elements as a row, in a csv file?
How to save a column of elements as a row, in a csv file?

Time:09-27

How can I save a column of elements, as a row/list, in a CSV file?

Here following the relevant part of my code...

import pandas as pd

df=pd.DataFrame(tbl,columns=['type','skill','job1','job2','m1','m2'])
df2=df['skill']

print(type(df2))
print(df2)

...and its corresponding result...

<class 'pandas.core.series.Series'>

1                statistics
26         highly motivated
32                     team
...
93                knowledge
94                  curious
95                      can
96                    lives
98             early talent
99           talent program
100         computer skills
101     process development
102             soft skills
103           early program
Name:  skill, dtype: object

My desired output would be a CSV file with all the words listed in a row, and delimited by a comma, i.e.

statistics, highly motivated, team, ..., knowledge, curious, can, lives, early talent, ...

CodePudding user response:

The pandas way would be to transpose a single column dataframe:

df2=df[['skill']]   # the double brackes ensure that df2 is a dataframe
df2.transpose.to_csv('out.csv', header=None)

This would generate (with your sample data):

statistics,highly motivated,team,knowledge,curious,can,lives,early talent,talent program,computer skills,process development,soft skills,early program

The good news is that is would correctly handle fields containing commas or new lines...

CodePudding user response:

You can do this... for any column to get data as required;

col_to_str = ", ".join(list(df['Column_Name']))
  • Related