简体   繁体   English

将“数据框”转换为“元组”但获得“列表”-Python

[英]Converting 'dataframe' to 'tuple' but getting a 'list' - Python

I want to convert a python dataframe into tuple. 我想将python数据框转换为元组。 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. ...提供的df2永远不会超过1个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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