我想獲取一個 csv 檔案,對其進行排序,然后將其另存為 csv。這是我到目前為止所擁有的,無法弄清楚如何將其寫入 csv 檔案
import csv
with open('test.csv','r') as f:
sample = csv.reader(f)
sort = sorted(sample)
for eachline in sort:
print (eachline)
uj5u.com熱心網友回復:
你不需要熊貓來做這樣簡單的事情:
# Read the input file and sort it
with open('input.csv') as f:
data = sorted(csv.reader(f))
# write to the output file
with open('output.csv', 'w', newline='\n') as f:
csv.writer(f).writerows(data)
python 中的元組按字典順序排序,這意味著它們按第一個值排序,如果它們與第二個值相等。您可以提供一個key按特定值排序的函式。
uj5u.com熱心網友回復:
我認為這樣的事情應該可以解決問題:
import pandas as pd
path = "C:/Your/file/path/file.csv"
df = pd.read_csv(path)
df = df.sort_values("variablename_by_which_to_sort", axis=0, ascending=True/False)
df.to_csv(path)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352891.html
下一篇:如何從csv檔案中推斷出候選鍵
