【问题标题】:Merge two identical CSV from the same directory - Python合并来自同一目录的两个相同的 CSV - Python
【发布时间】:2014-03-10 21:12:24
【问题描述】:

我在 CSV 中有两个具有相同结构的数据框。我想读取 CSV 并将它们合并以创建一个更大的数据框。目录中只有两个数据框。

第一个 CSV 被称为“first”:

ad   7   8
as   5   8
ty   9   y

第二个CSV称为“秒”:

ewtw   5   2
as     1   2
ty     4   9

我的代码是:

  import os
  import pandas as pd

  targetdir = "C:/Documents and Settings/USER01/Mis documentos/experpy"



  filelist = os.listdir(targetdir) 

  for file in filelist :
      df_csv=pd.read_csv(file) 
      big_df = pd.concat(df_csv)

不幸的是,它没有用。我该如何解决?

【问题讨论】:

  • 在 for 循环中创建一个 df_csvs 列表,将其命名为 l。然后在循环之外执行 pd.concat(l) 。 pd.concat 将列表作为参数而不是单个数据帧。如果需要,您可以在之后使用 drop_duplicates

标签: python csv pandas dataframe


【解决方案1】:

如果您只有两个 CSV,那么您可能只想使用 pd.merge

first = pd.read_csv( 'first.csv' ) # insert your file path
second = pd.read_csv( 'second.csv' ) 
big_df = (first, second, how='outer') # union of first and second

【讨论】:

  • 问题是我的问题的例子只是一个简化。我真的很想将 30 个 csv 合并到一个 csv 中。
  • (不幸的是我是新手,所以我只能在这里发表评论:)我认为 EdChum 的解决方案应该有效,尝试使用 targetdir+file 作为路径,而不仅仅是 file 您可能需要添加您的目标目录的额外斜线
【解决方案2】:

concat 采用一系列列表或字典:http://pandas.pydata.org/pandas-docs/dev/generated/pandas.tools.merge.concat.html,因此您可以做一个数据帧列表并将它们连接在一起以形成您的大 df:

filelist = os.listdir(targetdir) 

df_list=[]
big_df=None
for file in filelist :
    df_list.append(pd.read_csv(file))

big_df = pd.concat(df_list,ignore_index=True)

您也可以附加:

filelist = os.listdir(targetdir) 

big_df=None
for file in filelist :
    big_df.append(pd.read_csv(file), ignore_index=True)

我认为你应该改变你的路径:

targetdir = r'C:\Documents and Settings\USER01\Mis documentos\experpy'

以上使用原始字符串避免了Windows系统上斜杠的歧义解析

【讨论】:

  • 我已经尝试了你的第一个代码,但有一条消息说:“文件 first.csv 不存在”
  • 你能打印你的文件并检查它们是否有效吗,我不能帮你解决你的错误,因为它是你电脑本地的
  • 我不知道它是否有帮助,但“targetdir”不在我使用的 Ipython Notebook 的工作目录中。
  • 尝试将 targetDir 设置为此 targetdir = r'C:\Documents and Settings\USER01\Mis documentos\experpy'
猜你喜欢
  • 1970-01-01
  • 2012-04-29
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
相关资源
最近更新 更多