Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 合并中缺少列的CSV文件_Python_Csv_Pandas - Fatal编程技术网

Python 合并中缺少列的CSV文件

Python 合并中缺少列的CSV文件,python,csv,pandas,Python,Csv,Pandas,我是pandas和python的新手,所以我希望这会有意义 我已将网站中的多个表解析为多个CSV文件,不幸的是,如果解析数据的值不可用,则会将其从表中忽略。因此,我现在有了不同列数的CSV文件 我以前使用过read_csv()和to_csv(),当数据干净时,它就像一个符咒,但我在这里被难住了 我想有一种方法可以“映射”读取的数据,如果我首先将所有列标题输入到DF,然后将每个文件映射到主文件中的列 例如,一旦我使用了read_csv(),那么to_csv()将查看主合并文件,并将可用字段“映射到

我是
pandas
python
的新手,所以我希望这会有意义

我已将网站中的多个表解析为多个CSV文件,不幸的是,如果解析数据的值不可用,则会将其从表中忽略。因此,我现在有了不同列数的CSV文件

我以前使用过
read_csv()
to_csv()
,当数据干净时,它就像一个符咒,但我在这里被难住了

我想有一种方法可以“
映射
”读取的数据,如果我首先将所有列标题输入到
DF
,然后将每个文件映射到主文件中的列

例如,一旦我使用了
read_csv()
,那么
to_csv()
将查看主合并文件,并将可用字段“
映射到合并文件中的正确列

这是数据的简短版本:

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)
此代码合并数据,但由于列的数量不同,它们不在正确的位置


任何帮助都将不胜感激

尝试使用pandas concat[1]函数,该函数默认为外部联接(所有列都将出现,缺少的值将为NaN)。例如:

import pandas as pd

# you would read each table into its own data frame using read_csv
f1 = pd.DataFrame({'ID': [1], 'Price': [800], 'Name': ['Jim']})
f2 = pd.DataFrame({'ID': [2], 'Price': [500], 'Address': '1 Main St.', 'Name': ['Amanda']})

pd.concat([f1, f2]) # merged data frame

[1] 下面是一个完整的示例,演示如何使用
concat加载文件并合并它们:

In [297]:
import pandas as pd
import io
t="""ID, Price, Name
1, $800, Jim"""
df = pd.read_csv(io.StringIO(t), sep=',\s+')
t1="""ID, Price, Address, Name
2, $500, 1 Main St., Amanda"""
df1 = pd.read_csv(io.StringIO(t1), sep=',\s+')
pd.concat([df,df1], ignore_index=True)

Out[297]:
      Address  ID    Name Price
0         NaN   1     Jim  $800
1  1 Main St.   2  Amanda  $500

请注意,我传递了
ignore_index=True
,否则您将得到重复的索引项,我假设这不是您想要的,并且我假设在“文件1”的原始数据示例中,您的标题行中没有真正的尾随逗号:
ID、Price、Name、,
因此我从上面的代码中删除了它

它与熊猫无关,但是您可能会发现,您应该在
熊猫
中进行所有合并,使用
DataFrame.join
DataFrame.append
等方法。只在最后将结果写入文件。这将比试图通过将零碎部分分别写入文件来将其缝合在一起要轻松得多
pandas
有很多用于组合数据的工具,这样做会让您错过所有这些工具。感谢您为我指明了正确的方向。我能让它工作。