我想在.csv
文件中保存python列表,例如我有一个这样的列表:
['hello','how','are','you']
我想像这样保存它:
colummn,
hello,
how,
are,
you,
我尝试了以下内容:
myfile = open('/Users/user/Projects/list.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,'\n')
wr.writerow(pos_score)
答案 0 :(得分:34)
使用pandas to_csv
(http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html)
>>> import pandas as pd
>>> df = pd.DataFrame(some_list, columns=["colummn"])
>>> df.to_csv('list.csv', index=False)
答案 1 :(得分:10)
如果您想要不同行上的所有单词,您需要将熟食者设置为\n
:
l = ['hello','how','are','you']
import csv
with open("out.csv","w") as f:
wr = csv.writer(f,delimiter="\n")
wr.writerow(l)
输出:
hello
how
are
you
如果你想要一个逗号逗号:
with open("out.csv","w") as f:
wr = csv.writer(f,delimiter="\n")
for ele in l:
wr.writerow([ele+","])
输出:
hello,
how,
are,
you,
我建议只编写没有尾随逗号的元素,使用尾随逗号没有任何好处,但以后可能会导致问题。
答案 2 :(得分:2)
你可以将它作为dict的值传递给关键的'列'到DataFrame构造函数,然后在df:
上调用to_csv
In [43]:
df = pd.DataFrame({'column':['hello','how','are','you']})
df
Out[43]:
column
0 hello
1 how
2 are
3 you
In [44]:
df.to_csv()
Out[44]:
',column\n0,hello\n1,how\n2,are\n3,you\n'
答案 3 :(得分:0)
randss = np.random.choice(dsmodx.logss, 120, replace=False) # 120 表示 120 值 打印(兰兹)
randssdf = pd.DataFrame(randss, columns=["Log Ss"]) 将数据保存为excel randssdf.to_excel ('randomSs.xlsx', index = False)