我有一個目錄,其中所有 csv 檔案(按日期)都有各種水果的串列,并且有數量我想要一個(新)csv,在其中我只得到一種水果(比如蘋果的)資料。我已經嘗試了以下代碼,但它沒有給我所需的輸出。請幫忙。謝謝你。干杯。
串列1.csv
| Name | Qty |
| -------- | --- |
| apple |15 |
| apple |50 |
| mango |20 |
| grapes |49 |
串列2.csv
| Name | Qty |
| -------- | --- |
| apple |25 |
| apple |50 |
| Banana |34 |
| mango |20 |
| grapes |49 |
串列3.csv
| Name | Qty |
| -------- | --- |
| apple |125 |
| apple |530 |
| mango |20 |
| grapes |49 |
我想要一個我想要的 new.csv
| Name | Qty |
| -------- | --- |
| apple |15 |
| apple |50 |
| apple |25 |
| apple |50 |
| apple |125 |
| apple |530 |
import pandas as pd
import glob, os
path = ("E:/Data/Fdata")
all_files = glob.glob(path "/*.csv")
li=[]
for filename in all_files:
df=pd.read_csv(filename, index_col=None, header=0)
ndf = df[df["Name"].str.contains("Apple")]
li.append(ndf)
ndf.to_csv("E:/Data/Fdata/onlyapple.csv", index=True)
uj5u.com熱心網友回復:
- 將所有 csv 檔案讀取到
masterDataFrame - 過濾您想要的“名稱”并寫入
to_csv
import os
import pandas as pd
master = pd.DataFrame()
for file in [f for f in os.listdir(".") if f.endswith("csv")]:
master = master.append(pd.read_csv(file), ignore_index=True)
master[master["Name"].eq("apple")].reset_index(drop=True).to_csv("onlyapple.csv")
onlyapple.csv:
,Name,quantity,price
0,apple,15,500
1,apple,50,400
2,apple,15,500
3,apple,50,400
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/369396.html
