Search code examples
pythonpandas

Reorganize index and column DataFrame Pandas


I'm supposed to create a palindrome checker and convert them into dataFrame.

The code:

import pandas as pd 
# TODO: Check if the number is palindrome or not and convert them into DataFrame
n = [1,0,1] 
g = n == n[::-1]

a = pd.DataFrame(n)
a['Is Palindrome'] = g
a.transpose()

The Output:

                0       1       2
0               3       0       3
Is Palindrome   True    True    True

But the output I want the DataFrame to print is:

  0     1    2   Is Palindrome
  3     0    3   True

How do I build that?


Solution

  • You could use pandas to do it:

    df=pd.DataFrame(columns=['Number'],data=[101,202,301])
    df['Palindrome']=[str(i)==str(i)[::-1] for i in df['Number']]
    
    print(df)
    
       Number  Palindrome
    0     101        True
    1     202        True
    2     301       False
    

    Or if you want to transpose it:

    print(df.T)
                   0     1      2
    Number       101   202    301
    Palindrome  True  True  False