簡體   English   中英

將帶有選定列標題的 CSV 讀入 Python 中的一個 CSV 文件(逐行讀取)

[英]Read CSVs with selected column headers into one CSV file in Python (read by line)

我有個問題。 我想遍歷名稱中包含例如“usr666”的 csv 文件的文件夾,然后將它們加載到 pandas dataframe 中,然后僅通過以下示例標題將它們合並到一個文件中:

BT_usr666.csv: 
number|size|person|car    |
---------------------------
31     |2   |Ringo |Tesla  |
82     |3   |Paul  |Audi   |
93     |2   |John  |BMW    |
74     |3   |George|MG     |


RS_usr666.csv:

number|color|person|doors|car    |
---------------------------------
33    |black|Mick  |2    |Porsche|
12    |red  |Keith |4    |Saab   |
55    |blue |Ron   |6    |Volvo  |

into FINAL_usr666.csv

person|car    |
---------------
Ringo |Tesla  |
Paul  |Audi   |
John  |BMW    |
George|MG     |
Mick  |Porsche|
Keith |Saab   |
Ron   |Volvo  |

有任何想法嗎?

這個可以

這會在“.”中搜索文件。 即當前目錄並查找以 usr666 開頭的文件並執行您的要求

import pandas as pd
import os
x=pd.DataFrame()
for filename in sorted(os.listdir(".")):
    if filename.startswith("usr666"):
        y=pd.read_csv(filename)
        selected=y[["person","car"]]
        x=x.append(selected)
        x.to_csv('file1.csv',index=True)

您可以嘗試以下腳本。

代碼

import glob
import os

import pandas as pd

def get_final_df(files):
    df = pd.DataFrame()

    your_columns = ['person', 'car']

    for file in files:
        temp_df = pd.read_csv(file, usecols = your_columns)
        df = df.append(temp_df, ignore_index=True)

    return df

if __name__ == '__main__':
    wd = os.getcwd() # I've set this as working dir, you can change the path to your files.
    files = [file for file in glob.glob(os.path.join(wd, '*')) if 'usr666' in file]
    final_df = get_final_df(files)
    final_df.to_csv('final_df.csv', index=False) # Write to file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM