Home > Mobile >  Reorganize index and column DataFrame Pandas
Reorganize index and column DataFrame Pandas

Time:01-09

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 thing is I wanted to print the DataFrame as:

  0     1    2   Is Palindrome
  3     0    3   True

How do I build that?

CodePudding user response:

I think you just need to add the Is Palindrome column all the way at the end:

import pandas as pd 

n = [3,0,3] 
g = n == n[::-1]
a = pd.DataFrame(n)
a = a.transpose()
a['Is Palindrome'] = g

CodePudding user response:

Hi and welcome to Stackoverflow!

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
  •  Tags:  
  • Related