【发布时间】:2015-06-03 06:09:48
【问题描述】:
我是pandas 和python 的新手,所以我希望这是有道理的。
我已将网站上的multiple 表解析为multiple CSV files,不幸的是,如果该值不适用于解析的数据,则会从表中省略。因此,我现在拥有包含不同列数的 CSV 文件。
我过去使用过read_csv() 和to_csv(),当数据干净时,它就像一个魅力,但我被难住了。
如果我首先将所有列标题提供给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)
这段代码合并了数据,但是由于列数不同,所以放的地方不对……
任何帮助将不胜感激。
【问题讨论】:
-
它与熊猫无关,但您可能会发现有用stackoverflow.com/questions/26771999/…
-
您应该在
pandas中进行所有合并,使用DataFrame.join、DataFrame.append等内容。仅在最后将结果写入文件。这将比通过将零碎单独写入文件来尝试将其拼接在一起要少得多。pandas有很多 用于组合数据的工具,通过这种方式你会错过所有这些工具。