【问题标题】:Missing rows after splitting into chunks拆分成块后缺少行
【发布时间】:2021-01-21 00:18:31
【问题描述】:

我正在尝试将数据框拆分为 2000 行的块,我找到了这段代码,顺便说一句,我是 python 新手,它运行良好,但 最后一个数据框 它创建并导出到 excel,它全部被打乱了,我的意思是从第一个块到最后一个块之前的一个块,它按字母顺序排列,除了最后一个我发现所有乞求字母的地方,但它变得更糟.. . 我丢失了一些记录,我用这些块来自的数据框验证了这一点,但是在它被拆分后会丢失

max_rows = 2000
dataframes = []
while len(df_count) > max_rows:
    top = df_count[:max_rows]
    dataframes.append(top)
    df_count = df_count[max_rows:]
    n=0
else:
    dataframes.append(df)

with pd.ExcelWriter(output_path + "\\" + "Emails_" + date + ".xlsx") as writer:
    for _, frame in enumerate(dataframes):
        frame = frame["Email"]
        frame.to_excel(writer, sheet_name="DB" + str(_+1), index=False)

【问题讨论】:

    标签: python pandas split chunks


    【解决方案1】:

    else 上完全没看到数据框名称:

    max_rows = 2000
    dataframes = []
    while len(df_count) > max_rows:
        top = df_count[:max_rows]
        dataframes.append(top)
        df_count = df_count[max_rows:]
        n=0
    else:
        dataframes.append(df_count)
    
    with pd.ExcelWriter(output_path + "\\" + "Emails_" + date + ".xlsx") as writer:
        for _, frame in enumerate(dataframes):
            frame = frame["Email"]
            frame.to_excel(writer, sheet_name="DB" + str(_+1), index=False)
    

    【讨论】:

      【解决方案2】:

      使用iloc 分割数据框:

      df = pd.DataFrame(np.arange(10**6+10).reshape(int(10**6/2)+5, 2), columns=list('AB'))
      
      df.shape # (500005, 2)
      
      df_list = list()
      max_row = 2000
      for i in range(0, len(df), 2000):
          df_list.append(df.iloc[i: i + max_row])
      
      len(df_list) # 251
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 2016-02-16
        • 2020-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多