我是 pandas
和 python
的新手,所以我希望这有意义 .
我已经将 multiple
表从一个网站解析为 multiple CSV files
,不幸的是,如果该值不适用于已解析的数据,则表中省略了该表 . 因此,我现在拥有包含不同列数的CSV文件 .
我过去曾使用 read_csv()
和 to_csv()
,当数据干净时它就像一个魅力,但我在这里难倒 .
我想如果我首先使用所有列 Headers 输入 pandas DF
,那么可能有一种方法可以“ map
”读取数据,然后我将每个文件映射到主文件中的列 .
例如 . 一旦我使用 read_csv()
,那么 to_csv()
将查看主合并文件和“ map
”可用字段到合并文件中的正确列 .
这是数据的简短版本:
File 1:
ID, Price, Name,
1, $800, Jim
File 2:
ID, Price, Address, Name
2, $500, 1 Main St., Amanda
Desired Output:
ID, Price, Adress, Name
1, $800, , Jim
2, $500, 1 Main St., Amanda
这是我到目前为止的代码 .
mypath='I:\\Filepath\\'
#creating list of files to be read, and merged.
listFiles = []
for (dirpath, dirnames, filenames) in walk(mypath):
listFiles.extend(filenames)
break
# reading/writing "master headers" to new CSV using a "master header" file
headers = pd.read_csv('I:\\Filepath\\master_header.csv', index_col=0)
with open('I:\\Filepath\\merge.csv', 'wb') as f:
headers.to_csv(f)
def mergefile(filenames):
try:
# Creating a list of files read.
with open('I:\\Filepath\\file_list.txt', 'a') as f:
f.write(str(filenames)+'\n')
os.chdir('I:\\Filepath\\')
# Reading file to add.
df = pd.read_csv(filenames, index_col=0)
# Appending data (w/o header) to the new merged data CSV file.
with open('I:\\Filepath\\merge.csv', 'a') as f:
df.to_csv(f, header=False)
except Exception, e:
with open('I:\\Filepath\\all_error.txt', 'a') as f:
f.write(str(e)+'\n')
for eachfilenames in listFiles:
mergefile(eachfilenames)
此代码合并数据,但由于列数不同,它们不在正确的位置......
任何帮助将不胜感激 .
2 回答
这是一个完整的示例,演示如何加载文件并使用
concat
合并它们:请注意,我传递了
ignore_index=True
否则您将获得重复的索引条目,我认为这不是您想要的,我也在您的 Headers 行中有一个尾随逗号:ID, Price, Name,
所以我从上面的代码中删除了它尝试使用pandas concat [1]函数,该函数默认为外连接(所有列都将存在,缺少的值将为NaN) . 例如:
[1] http://pandas.pydata.org/pandas-docs/stable/merging.html