简体   繁体   English

如何在 csv 文件中将一列元素保存为一行?

[英]How to save a column of elements as a row, in a csv file?

How can I save a column of elements, as a row/list, in a CSV file?如何将一列元素作为行/列表保存在 CSV 文件中?

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 , ie我想要的 output 将是一个 CSV 文件,其中所有单词都列在一行中,并用逗号分隔,即

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

The pandas way would be to transpose a single column dataframe: pandas 方法是转置单列 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...好消息是它将正确处理包含逗号或换行符的字段......

You can do this... for any column to get data as required;您可以这样做...对于任何列以根据需要获取数据;

col_to_str = ", ".join(list(df['Column_Name']))
# Export as CSV
import pandas as pd
df1 = pd.DataFrame({"Column_Name":[col_to_str]})
df1.to_csv("export.csv",index=False)

Hope this Helps...希望这可以帮助...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM