【问题标题】:I am appending csv files in the format我正在附加格式的 csv 文件
【发布时间】:2018-02-26 10:25:35
【问题描述】:

我正在使用这种格式的 python 从路径中附加多个 csv 文件

A  B  C  date
2  3  4  20180213
5  6  7  20170213

A  B  C  date
3  4  9  20170210
3  2  1  20180211

我使用的代码是:

import os 
import datetime 
import glob 
import pandas as pd 
import csv 

yyyymmdd = (dt.date.today()-timedelta(days=1)).strftime('%Y%m%d') 

for filename in glob.glob(os.path.join("/xyz/abc/*/*.csv")):
    df2=pd.read_csv(filename).assign(date=yyyymmdd)
    df2 = df2.append(df2, ignore_index=True)
    df2=df2.drop_duplicates()
    print(df2)

我得到的结果是:

A  B  C  date
2  3  4  20180213
5  6  7  20170213
A  B  C  date
3  4  9  20170210
3  2  1  20180211

即标题重复。而我想要它的格式:

A  B  C  date
2  3  4  20180213
5  6  7  20170213
3  4  9  20170210
3  2  1  20180211

【问题讨论】:

  • assign 调用中的所有行的 date 有何不同?此外,timedelta 既没有定义也没有导入方法。确保代码完全可编译以供我们重现。

标签: python pandas csv


【解决方案1】:

看看read_csv函数here的header参数,我的建议是跳过使用header=None的标题,除了第一个文件。

【讨论】:

    【解决方案2】:

    考虑构建一个数据帧列表或字典,然后使用pandas.concat 将所有列表项连接在一起,而不会出现标题问题:

    ...
    df_list = []
    
    for filename in glob.glob(os.path.join("/xyz/abc/*/*.csv")):
        tmp = pd.read_csv(filename).assign(new_date=yyyymmdd)
        df_list.append(tmp)        # LIST APPEND
        print(tmp)
    
    final_df = pd.concat(df_list, ignore_index=True).drop_duplicates()
    

    【讨论】:

      【解决方案3】:

      我知道我错了。 print(df2) 进入了循环。删除之前的标签后,它起作用了。

      import os 
      import datetime 
      import glob 
      import pandas as pd 
      import csv 
      
      yyyymmdd = (dt.date.today()-timedelta(days=1)).strftime('%Y%m%d') 
      
      for filename in glob.glob(os.path.join("/xyz/abc/*/*.csv")):
          df2=pd.read_csv(filename).assign(date=yyyymmdd)
          df2 = df2.append(df2, ignore_index=True)
          df2=df2.drop_duplicates()
      print(df2)
      

      【讨论】:

        猜你喜欢
        • 2019-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        • 2016-11-19
        相关资源
        最近更新 更多