[英]How to save a column of elements as a row, in a csv file?
如何將一列元素作為行/列表保存在 CSV 文件中?
下面是我的代碼的相關部分......
import pandas as pd
df=pd.DataFrame(tbl,columns=['type','skill','job1','job2','m1','m2'])
df2=df['skill']
print(type(df2))
print(df2)
...及其相應的結果...
<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
我想要的 output 將是一個 CSV 文件,其中所有單詞都列在一行中,並用逗號分隔,即
statistics, highly motivated, team, ..., knowledge, curious, can, lives, early talent, ...
pandas 方法是轉置單列 dataframe:
df2=df[['skill']] # the double brackes ensure that df2 is a dataframe
df2.transpose.to_csv('out.csv', header=None)
這將生成(使用您的示例數據):
statistics,highly motivated,team,knowledge,curious,can,lives,early talent,talent program,computer skills,process development,soft skills,early program
好消息是它將正確處理包含逗號或換行符的字段......
您可以這樣做...對於任何列以根據需要獲取數據;
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)
希望這可以幫助...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.