【问题标题】:creating a list of tuples from dataframe entries从数据框条目创建元组列表
【发布时间】:2020-07-31 20:29:08
【问题描述】:

我有一个数据框df

movie_title          director_name     ...   oscar_wins   oscar_nominees
El Mariachi          Robert Rodriguez  ...       0             0
My Date with Drew    Jon Gunn          ...       0             0

我想要做的是创建一个元组列表,其中每个元组都是数据帧的一行。所以输出应该是这样的:

[(El Mariachi, Robert Rodriguez, ... , 0, 0), (My Date with Drew, Jon Gunn, ..., 0, 0) ...]

我尝试过迭代长度和列名,但没有成功。

list(zip(range(len(df)), column_names)

虽然我知道它为什么不起作用,但我不确定如何实现我想要的。有没有人可以帮助我或为我提供修复?

谢谢,非常感谢!

【问题讨论】:

    标签: python pandas list loops


    【解决方案1】:

    您也可以这样做:

    [tuple(x) for x in df.to_numpy()]
    # [('El Mariachi', 'Robert Rodriguez', 0, 0), ('My Date with Drew', 'Jon Gunn', 0, 0)]
    

    最快的方法是使用to_records():

    df.to_records(index=False).tolist()
    

    【讨论】:

      【解决方案2】:
       all_rows=[]
       for index, row in df.iterrows():
              all_rows.append(tuple(row))
      

      说明:使用 for 循环和 iterrows(),可以遍历数据帧。两个元素索引(表示 df 的索引)和行(描述样本的行,它是一个列表)。现在使用 tuple(),将此行(列表类型对象)转换为元组并附加到新列表“all_rows”中

      【讨论】:

        【解决方案3】:

        列表理解的解决方案:

        L = [tuple(x) for x in df.values.tolist()]
        print (L)
        [('El Mariachi', 'Robert Rodriguez', 0, 0), ('My Date with Drew', 'Jon Gunn', 0, 0)]
        

        【讨论】:

          【解决方案4】:

          只需将列表中的值和map 内部列表返回到元组:

          list(map(tuple,df.values.tolist()))
          # [('El Mariachi', 'Robert Rodriguez', 0, 0), ('My Date with Drew', 'Jon Gunn', 0, 0)]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-13
            • 1970-01-01
            • 2021-04-03
            • 1970-01-01
            • 1970-01-01
            • 2019-10-10
            相关资源
            最近更新 更多