pythonpandasdataframepython-3.11

How to avoid fragmentation warning when moving a column to position 0?


single statement of

df.insert(0, 'time', df.pop('time'))

on large dataframe causing

warning: PerformanceWarning: DataFrame is highly fragmented.

is there away to move a column to position ZERO to avoid this warning.


Solution

  • Consider this dataframe:

       column1  column2  time
    0        1        2     3
    1        4        5     6
    

    You can reorder the columns and put the time column first like this:

    df = df[["time", *df.columns.difference(["time"])]]
    print(df)
    

    Prints:

       time  column1  column2
    0     3        1        2
    1     6        4        5