简体   繁体   中英

Converting 'dataframe' to 'tuple' but getting a 'list' - Python

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM