0

I want to convert a python dataframe into tuple. I tried to follow the method mentioned in below link, but what I am getting in return is a 'list'. - Pandas convert dataframe to array of tuples

def answer_six():
   df1 = df['% Renewable']
   df2=df1.reset_index()
   print(df2)
   print('df2 type -',type(df2))
   t1 = [tuple(x) for x in df2.values]
   print ('t1 type-',type(t1))
   return t1

answer_six()

result

  Country % Renewable
  0  Brazil      69.648
  df2 type - <class 'pandas.core.frame.DataFrame'>
  t1 type- <class 'list'>
  Out[9]:
  [('Brazil', 69.64803)]

Can you kindly help to convert it into a tuple ?

Rajat Panda
  • 129
  • 1
  • 3
  • 14
  • Possible duplicate of [Pandas convert dataframe to array of tuples](https://stackoverflow.com/questions/9758450/pandas-convert-dataframe-to-array-of-tuples) – Daan Jun 04 '17 at 08:26

1 Answers1

1

You could change this line:

t1 = [tuple(x) for x in df2.values]

To this:

t1 = [tuple(x) for x in df2.values][0]

...provided df2 will never have more than 1 element.

Remolten
  • 2,614
  • 2
  • 25
  • 29
  • Thank you Remolten for the quick reply!! That worked. What if there are more than one element ? How do I convert multiple rows of data into array of tuples. – Rajat Panda Jun 04 '17 at 00:29
  • Your code will already create a *list* of tuples, as you can see in your result section. – Remolten Jun 04 '17 at 00:31