繁体   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