我有一个示例csv文件,其中包含一些未排序的随机数。我想从csv文件中排序数据,我必须将排序后的数据写入新的csv文件。问题是,如果我有像
这样的数据 3,
65,
20,
21,
19,
34,
8,
0,
22
python只根据第一个数字进行排序。如果我打印出已排序的数据,我会得到以下输出。
['0'], ['19'], ['20'], ['21'], ['22'], ['3'], ['34'], ['65'], ['8']
这是基于第一个数字进行排序。
我希望将已排序的数据写入新的csv文件。
提前感谢。
答案 0 :(得分:0)
您可以使用numpy
来处理类型转换。这样的事情应该有效:
import numpy as np
arr = np.genfromtxt('in.csv', delimiter=',')
arr.sort()
np.savetxt('out.csv', arr, delimiter=',')
答案 1 :(得分:0)
鉴于你有可选的空格和逗号,这应该有效:
with open('in.csv') as infile, open(out.csv) as outfile:
data = infile.readlines() #read data into list line by line
nums = [''.join([c for c in i if c.isdigit()]) for i in data] #extract only the numbers from lines
result = sorted(nums, key=int) #sort the numbers by their integer value ascending (default)
outfile.write(',\n'.join(result)) #write result to file adding `,\n` to end of each number - \n being the newline
答案 2 :(得分:0)
import csv
with open('sample.csv') as file:
reader = csv.reader(file)
i = 0
new_data = []
for row in reader:
if(row[0]!='' and row[0].isdigit()):
new_data.append(row[0])
new_data.sort(key=int)
print(new_data)
with open('newfile.csv', 'w') as newfile:
writer = csv.writer(newfile)
writer.writerow(new_data)
上面的代码对我有用。 感谢所有的贡献。