我正在嘗試在 python 中讀取 100 多個 csv 檔案以保留 TOP 500 行(它們每個都有超過 55,0000 行)。到目前為止,我知道如何做到這一點,但我需要將每個修改過的檔案保存在回圈中,并以 csv 格式保存其自己的檔案名。因為通常我可以將連接的資料幀輸出到一個大的 csv 檔案,但這次我需要基本上截斷每個 csv 檔案,只保留前 500 行并保存每一行。
這是我到目前為止的代碼:
import pandas as pd
import glob
FolderName = str(input("What's the name of the folder are you comparing? "))
path = str(input('Enter full path of the folder: '))
#r'C:\Users\si\Documents\UST\AST' # use your path
all_files = glob.glob(path "/*.csv")
#list1 = []
d = {}
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0, nrows=500)
#list1.append(df)
d[filename] = df.columns
#frame = pd.concat(list1, axis=0, ignore_index=True)
frame = pd.DataFrame.from_dict(d, orient='index')
output_path = r'C:\Users\si\Downloads\New\{}_header.xlsx'.format(FolderName)
frame.to_excel(output_path)
uj5u.com熱心網友回復:
資料框可以寫入和讀取 CSV。to_csv因此,只需使用相同的檔案名創建和呼叫。
import pandas as pd
import glob
FolderName = str(input("What's the name of the folder are you comparing? "))
path = input('Enter full path of the folder: ')
all_files = glob.glob(path "/*.csv")
for filename in all_files:
pd.read_csv(filename, index_col=None, header=0, nrows=500).to_csv(filename)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474541.html
上一篇:用R中的缺失資料填充資料框
