Search code examples
pythonpandas

How to reverse the value of column in a dataframe?


Given a dataframe with one columm "Name" and two rows.

Input: Name
       ABCD
       XYZ

Output: Name
        DCBA
        ZYX

I have searched online and the solution is to reverse the row/column order. Kindly suggest how can I reverse the value in a column in A DataFrame


Solution

  • You have to use a loop. Assuming strings, you could use apply:

    df['Name'] = df['Name'].apply(lambda x: x[::-1])
    

    or a list comprehension:

    df['Name'] = [x[::-1] for x in df['Name']]
    

    Output:

       Name
    0  DCBA
    1   ZYX
    

    If you don't have only strings, a safer approach would be to check for the type:

    df['Name'] = df['Name'].apply(lambda x: x[::-1] if isinstance(x, str) else x)
    # or
    df['Name'] = [x[::-1] if isinstance(x, str) else x for x in df['Name']]