【问题标题】:Pandas DataFrame Apply Function and Save every N stepsPandas DataFrame 应用函数并保存每 N 步
【发布时间】:2023-02-08 21:29:36
【问题描述】:

我的 DF 非常大,是否有一种很好的方法(不是循环)来修改 DF 中的某些值并保存每 N 个步骤,例如

def modifier(x):
   x = x.split() # more complex logic is applied here
   return x

df['new_col'] = df.old_col.apply(modifier)

有没有一种很好的方法可以向修饰函数添加一些代码,每 10,000 行

df.to_pickle('make_copy.pickle')

会叫吗?

【问题讨论】:

    标签: python pandas apply


    【解决方案1】:

    为了保存每一行,问题是确保边缘情况得到正确处理(因为最后一部分可能不是全尺寸部分)。使用讨论的方法here 然后你可以按照以下几行做一些事情。虽然有一个循环,但它只适用于每个部分。请注意,如果您保存每个部分,那么您需要一种机制来以新名称保存每个部分(或者附加到 DF 列表并保存)。

    from more_itertools import sliced   # this module might need to be installed using pip
    SLICE_SIZE = 10000
    
    slices = sliced(range(len(df)), SLICE_SIZE)
    
    for index in slices:
        df_slice = df.iloc[index]
        print(df_slice)          # or do anything you want with the section of the DF such as save it as required
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2023-01-23
      • 1970-01-01
      相关资源
      最近更新 更多