【问题标题】:Convert list to data frame in python在python中将列表转换为数据框
【发布时间】:2021-12-13 08:39:52
【问题描述】:

我正在尝试从下面的列表中创建一个数据框,其中第一列是“网页”,它是索引号,第二列是“destination_nodes”,它是 dest_nodes 列表。

for col in range(10001):
    print(col)
    dest_nodes = M.index[M[col] == 1.0].tolist()
    print(dest_nodes)

print(col) 和 print(dest_nodes) 的输出示例如下所示:

0
[2725, 2763, 3575, 4377, 6221, 7798, 7852, 8014, 8753, 9575]
1
[137, 753, 1434, 2182, 3163, 3646, 3684, 3702, 3966, 4353, 4410, 5029, 5610, 5671, 6149, 6505, 6835, 7027, 7030, 7127, 7724, 7876, 8006, 8676, 8821, 9069, 9226, 9321]
2
[473, 1843, 6748]
3
[67, 433, 537, 1068, 1118, 1191, 1236, 1953, 2285, 2848, 3296, 3816, 4155, 4507, 4704, 4773, 5028, 5333, 5341, 5613, 5656, 5858, 6068, 6169, 6239, 7367, 7897, 7909, 8973, 9113, 9576, 9799, 9909]
4
[]

我尝试了以下方法,但似乎没有满足我的要求。

dest_node = pd.DataFrame (col, dest_nodes, columns = ["webpage","destination_nodes"])

我想要的输出数据框是这样的:

如果我能得到任何帮助,我将不胜感激!

【问题讨论】:

  • 您希望目标节点中的第 4 行为空吗?
  • @LakpaTamang 是的,我希望它是空的

标签: python pandas list dataframe


【解决方案1】:

我会使用列表推导来设置dictionary

df = pd.DataFrame({col:[M.index[M[col] == 1.0].tolist()] for col in range(10001)}, index="nodes")
df.index.name = "website"

print(df.traspose())

【讨论】:

    【解决方案2】:

    这行得通

    # Make list
    colLst = [i for i in range(10001)]
    dest_nodesLst =[M.index[M[col] == 1.0].tolist() for col in range(1001)]
    
    # Make data frame
    dic = {"col":colLst,"M":dest_nodesLst}
    dest_node = pd.DataFrame(data=dic)
     
    # print head of dataframe
    print(dest_node.head())
    

    【讨论】:

      【解决方案3】:

      您可以使用 zip 来实现。像这样

      pd.DataFrame(zip(col, dest_nodes), columns=["webpage","destination_nodes"])
      

      如果您想删除括号并想要与图像中显示的完全相同的表示,请先运行以下代码,然后创建一个 DataFrame。

      dest_nodes = [str(l1).replace('[', '').replace(']','') for l1 in dest_nodes]
      

      【讨论】:

        【解决方案4】:

        也许你可以直接使用M

        df = pd.DataFrame(
                 {'webpage': M.columns,
                 'destination_nodes': M.eq(1).apply(lambda x: M[x].index.tolist())}
        )
        print(df)
        
        # Output
          webpage destination_nodes
        0       0            [0, 2]
        1       1            [0, 1]
        2       2                []
        3       3               [1]
        4       4            [1, 2]
        

        设置:

        data = {'0': [1, 0, 1],
                '1': [1, 1, 0],
                '2': [0, 0, 0],
                '3': [0, 1, 0],
                '4': [0, 1, 1]}
        M = pd.DataFrame(data)
        print(M)
        
        # Output:
           0  1  2  3  4
        0  1  1  0  0  0
        1  0  1  0  1  1
        2  1  0  0  0  1
        

        【讨论】:

          猜你喜欢
          • 2016-02-05
          • 2021-04-12
          • 2021-04-19
          • 1970-01-01
          • 2020-07-23
          • 2018-10-30
          • 2020-05-07
          • 1970-01-01
          相关资源
          最近更新 更多