【问题标题】:how to take a list with range of values and convert into a dataframe如何获取具有值范围的列表并转换为数据框
【发布时间】:2020-10-14 19:01:34
【问题描述】:
list=['1','matt','26','teacher','yes','2','tom','26','teacher','no','3','stuart','28','teacher','No']

如何从列表中选择前五个值并制作成这样的数据框:

number  name    age   type      employed
1       matt    26    teacher    yes
2       tom     26    teacher    no
3       staurt  28    teacher    No

【问题讨论】:

    标签: python pandas list dataframe lambda


    【解决方案1】:

    您已将lst 分成大小均匀的块,在您的情况下为 5。

    pd.DataFrame([lst[i:i+5] for i in range(0,len(lst),5)],
                 columns = ['number','name','age','type','employed'])
    

    使用iter对其进行概括,使其也可以与生成器一起使用

    it = iter(lst)
    pd.DataFrame(iter(lambda: list(islice(it,5)),[]),
                 columns = ['number','name','age','type','employed'])
    

    输出:

      number    name age     type employed
    0      1    matt  26  teacher      yes
    1      2     tom  26  teacher       no
    2      3  stuart  28  teacher       No
    

    【讨论】:

      【解决方案2】:
      import pandas as pd 
      import numpy as np
      edata =['1','matt','26','teacher','yes','2','tom','26','teacher','no','3','stuart','28','teacher','No']
      n_rows = 3
      n_cols = 5
      data = np.array(edata).reshape(n_rows,n_cols)
      data = pd.DataFrame(data)
      data.columns =['number','name','age','type','employed']
      

      【讨论】:

        【解决方案3】:

        你可以试试:

        pd.DataFrame(np.array(lst).reshape(-1,5), 
                     columns=['number','name','age','type','employed'])
        

        输出:

          number    name age     type employed
        0      1    matt  26  teacher      yes
        1      2     tom  26  teacher       no
        2      3  stuart  28  teacher       No
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-18
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          • 2019-04-25
          • 1970-01-01
          • 1970-01-01
          • 2019-05-29
          相关资源
          最近更新 更多