【问题标题】:Append columns of dataframe to list as lists将数据框的列附加到列表中
【发布时间】:2021-02-06 23:36:21
【问题描述】:

我有一个数据框:

col1   col2  col3
1       7     8
1.5     6.7   9
1.24    5.5   8.8

我想编写一个函数,它将这些列值作为列表添加到列表中。所以会有一个嵌套列表,包含这些值:

[[1,1.5,1.24], [7,6.7,5.5], [8,9,8.8]]

我写了这个函数,但是它不起作用:

def func1(df):
    my_list=[]
    for i in df:
        my_list.append(i)

【问题讨论】:

    标签: python python-3.x pandas function dataframe


    【解决方案1】:

    这里是解决方案。您只需将数据框名称更改为“df”:

    lst=[]
    for i in range(len(df.columns)):
        takelists = df.iloc[:, i].tolist()
        lst.append(takelists)
    
    print(last)
    

    例子:

      Column Column2 Column3
    0   1      4       7
    1   2      5       8
    2   3      6       9
    
    Out[129]:
    
    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    【讨论】:

      【解决方案2】:

      您可以通过结合to_numpy()tolist 方法来做到这一点:

      values = df.to_numpy().T.tolist()
      print(values)
      

      输出

      [[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]
      

      【讨论】:

        【解决方案3】:

        Pandas DataFrame 可以通过调用x.tolist() 转换为 Python 列表。你也可以使用list(x)

        import pandas as pd
        
        datadict = {'col1': [1, 1.5, 1.24], 'col2': [7, 6.7, 5.5], 'col3': [8, 9, 8.8]}
        df = pd.DataFrame(datadict)
        
        print(f"DataFrame:\n{df}")
        
        # 1st way:
        def func1(df_):
            my_list = list()
            for col in df_.columns:
                my_list.append(df_[col].tolist())
            return my_list
        
        result1 = func1(df)
        print(f"Using x.tolist():\n{result1}")
        
        # 2nd way:
        func2 = lambda df_: [list(df_[col]) for col in df_.columns]
        
        result2 = func2(df)
        print(f"Using list(x):\n{result2}")
        

        输出:

        DataFrame:
           col1  col2  col3
        0  1.00   7.0   8.0
        1  1.50   6.7   9.0
        2  1.24   5.5   8.8
        
        Using x.tolist():
        [[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]
        
        Using list(x):
        [[1.0, 1.5, 1.24], [7.0, 6.7, 5.5], [8.0, 9.0, 8.8]]
        

        【讨论】:

          猜你喜欢
          • 2019-09-08
          • 2019-10-12
          • 2021-05-01
          • 2012-09-26
          • 2022-01-17
          • 1970-01-01
          • 2016-08-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多