个csv文件导入到pandas中并连接到一个DataFrame中

个csv文件导入到pandas中并连接到一个DataFrame中

本文介绍了将多个csv文件导入到pandas中并连接到一个DataFrame中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从目录中读取几个csv文件到pandas,并将它们连接成一个大的DataFrame。我没有能够弄清楚它。这是我到目前为止:

I would like to read several csv files from a directory into pandas and concatenate them into one big DataFrame. I have not been able to figure it out though. Here is what I have so far:

import glob
import pandas as pd

# get data file names
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")

dfs = []
for filename in filenames:
    dfs.append(pd.read_csv(filename))

# Concatenate all data into one DataFrame
big_frame = pd.concat(dfs, ignore_index=True)

我想我需要一些帮助

推荐答案

如果您的所有 csv 文件中有相同的列,可以试试下面的代码。
我添加了 header = 0 ,以便在读取 csv 后,第一行可以分配为列名。

If you have same columns in all your csv files then you can try the code below.I have added header=0 so that after reading csv first row can be assigned as the column names.

path =r'C:\DRO\DCL_rawdata_files' # use your path
allFiles = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list_ = []
for file_ in allFiles:
    df = pd.read_csv(file_,index_col=None, header=0)
    list_.append(df)
frame = pd.concat(list_)

这篇关于将多个csv文件导入到pandas中并连接到一个DataFrame中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:07