import csv
with open('test.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[1]] += 1
for row in data:
if counter[row[1]] >= 4:
writer = csv.writer(open("test1.csv", "wb"))
writer.writerows(row)
我的输出很奇怪!这段代码有什么问题?
答案 0 :(得分:35)
我知道问题是询问你的“csv”软件包实现,但是对于你的信息,有些选项更简单 - 例如numpy。
import numpy as np
np.savetxt('data.csv', (col1_array, col2_array, col3_array), delimiter=',')
(这个答案在6年后发布,为了后人的缘故。)
在与你所问的类似的不同情况下,假设你有两个这样的列:
names = ['Player Name', 'Foo', 'Bar']
scores = ['Score', 250, 500]
你可以这样保存:
np.savetxt('scores.csv', [p for p in zip(names, scores)], delimiter=',', fmt='%s')
scores.csv
看起来像这样:
Player Name,Score
Foo,250
Bar,500
答案 1 :(得分:33)
使用csv.writer
:
import csv
with open('thefile.csv', 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
if counter[row[0]] >= 4:
writer.writerow(row)
答案 2 :(得分:5)
你可以关闭文件而不是csv.writer对象,它应该是:
f = open(fileName, "wb")
writer = csv.writer(f)
String[] entries = "first*second*third".split("*");
writer.writerows(entries)
f.close()
答案 3 :(得分:2)
一个简单的例子就是:
writer = csv.writer(open("filename.csv", "wb")) String[] entries = "first#second#third".split("#"); writer.writerows(entries) writer.close()
答案 4 :(得分:0)
我就是这样做的
import csv
file = open('???.csv', 'r')
read = csv.reader(file)
for column in read:
file = open('???.csv', 'r')
read = csv.reader(file)
file.close()
file = open('????.csv', 'a', newline='')
write = csv.writer(file, delimiter = ",")
write.writerow((, ))
file.close()
答案 5 :(得分:0)
如果您有Pandas Dataframe,可以将其保存为以下内容
df.to_csv(r'/dir/filename.csv')
答案 6 :(得分:-2)
这将提供准确的输出
import csv
import collections
with open('file.csv', 'rb') as f:
data = list(csv.reader(f))
counter = collections.defaultdict(int)
for row in data:
counter[row[0]] += 1
writer = csv.writer(open("file1.csv", 'w'))
for row in data:
if counter[row[0]] >= 1:
writer.writerow(row)