pythonpandas

Pandas - shifting columns to a specific column position


I have a simple dataframe:

data = [[2025, 198237, 77, 18175],
        [202, 292827, 77, 292827]]

I only want the 1st and 4th columns and I don't want header or index labels:

df = pd.DataFrame(data).iloc[:,[0,3]]
print(df.to_string(index=False, header=False))

Output is the following:

2025  18175
 202 292827

How do I line up my first column in column 3 (left-justified) and line up my second column in column 10 (left-justified)? Since i'm calling the to_string method, which is converting the dataframe to a string representation, shouldn't I be able to use ljust? I'm not able to produce the desired output, which would be:

   2025   18175  
   202    292827 

Solution

  • Define a formatting function with a single arg and apply to relevant columns

    import pandas as pd
    
    mw=7
    def left_align(x):
            return f"{x: <{mw}}"
    
    
    data = [[2025, 198237, 77, 18175],
            [202, 292827, 77, 292827]]
    
    
    df = pd.DataFrame(data).iloc[:,[0,3]]
    # get length of max value
    mw = len(str(df.max(numeric_only=True).max()))
    
    #print(mw)
    print(df.to_string(index=False, header=False, formatters=[left_align, left_align]))
    

    Result

    2025   18175 
    202    292827