Hi
想請問如何用Python計算csv某一/列的個數,由於檔案有很多,不想要一個個打開來看...
非常緊急,麻煩求解,謝謝各位!
(圖片如下,想要計算第一列總共個數為多少? Ps.A1不包含)
import os
import pandas as pd
files=os.listdir("<your_dir_path>")
files=[f + "<your_dir_path>" for f in files if f.endswith("csv")]
#method1
for f in files:
df=pd.read_csv(f)
print(f, len(df))
#method2
for f in files:
with open(f, "r", encoding="utf8") as fr:
data=fr.read()
data=data.split("\n")
print(f, len(data.split(",")) # notice: if your data have comma the standard csv file will use "," to split data including this ". as a result this method may doesn't work or you should modify this yourself.
update
files=[f + "<your_dir_path>" for f in files if f.endswith("csv")]
=>
files=[os.path.join("<your_dir_path>", f) for f in files if f.endswith("csv")]
if you want to exclude A1 you can minus 1 your self
pandas在讀 csv 的時候可以利用 header 參數指定row1是標題。
或是用 skiprows 參數去略過第1列。
Hi GoatWang
這計算出來的個數是否為直向的那一行?若要計算橫向(第一列)的話,該如何操作呢?
謝謝。
抱歉早上趕上班,在手機上打的,有些錯誤。
上面的回應是OK的。
也可以這樣 https://gas-stationsnearme.com/chevron/