【问题标题】:How to create multiple dataframes and concatenate them?如何创建多个数据框并将它们连接起来?
【发布时间】:2021-03-24 00:53:08
【问题描述】:

我正在尝试创建一个循环,打开 24 个 csv 文件并将它们连接成一个并创建一个最终的 csv 文件。

我尝试了以下所有方法,直到我需要将它们连接起来......

#Filename
file = '160321-PCU'
fileout = file+'ALL.csv'

#Foor loop to read_csv 24 times - this works... this prints me the dfs
for i in range(1,25):
  filename = file+str(i)+'.csv'
  df = pd.read_csv(gdrive_url+filename, sep=';',
                   names=['Date','Time_Decimal','Parameter','Value'])

  #This is my attempt to concatenate the dfs...
  df_concat = pd.concat([df])

#But as soon as I execute the code below to create ONE csv file to one file, it
#just gives me the 160321-PCU24 df... no concatenate...
df_concat.to_csv(gdrive_url_out+fileout, index=True)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    concat 函数需要输入一系列要连接的对象。您的代码仅传递一个对象,即最近读取文件中的数据帧。请参阅下面的修改代码,它创建一个空数据帧并连接从 csv 读取的每个数据帧:

    import pandas as pd
    
    data1 = ['2020', '4.05', 'Param1', 'Val1']
    data2 = ['2021', '3.59', 'Param2', 'Val2']
    
    with open('file_1.csv', 'w') as f:
        f.write(','.join(data1))
        
    with open('file_2.csv', 'w') as f:
        f.write(','.join(data2))
        
    fileout = 'file_3.csv'
    
    df_concat = pd.DataFrame()
    
    for i in range(1,3):
      filename = 'file_' + str(i) + '.csv'
      df = pd.read_csv(filename, sep=',',
                       names=['Date','Time_Decimal','Parameter','Value'])
      df_concat = pd.concat([df_concat, df])
    
    df_concat.to_csv(fileout, index=True)
    print(df_concat)
    

    【讨论】:

    • 嗨@TBaggins,谢谢,我试过了,但输出似乎不正确。基本上不是在时间戳 12:00 AM 有一行,而是在 12:00 AM 有 24 行,等等......
    • 查看已编辑的答案,其中包括 csv 文件的内容。
    【解决方案2】:

    我稍微更改了您的代码。我无法复制您的问题,但希望以下方法有效:

    #Filename
    file = '160321-PCU'
    fileout = file+'ALL.csv'
    
    # Empty list to put in the dfs
    li = []
    
    #For loop to read_csv 24 times - this works... this prints me the dfs
    for i in range(1,25):
      filename = file+str(i)+'.csv'
      df = pd.read_csv(gdrive_url+filename, sep=';',
                       names=['Date','Time_Decimal','Parameter','Value']
      li.append(df) # add it to the list of dataframes
    
    all_dfs = pd.concat(li, axis=0, ignore_index=True)  # concat all dataframes imported
    

    然后您可以将它们导出到您的文件夹中:

    all_dfs.to_csv(gdrive_url_out+fileout, index=True)
    

    也请查看here 以了解类似问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多