【问题标题】:adding lists with different length to a new dataframe将不同长度的列表添加到新数据帧
【发布时间】:2020-09-11 23:34:39
【问题描述】:

我有两个不同长度的列表,例如 a=[1,2,3]b=[2,3]

我想从他们那里生成一个pd.DataFrame,方法是在列表的开头填充nan,如下所示:

   a  b
1  1  nan 
2  2  2
3  3  3

我会很感激这样做的一种干净的方式。

【问题讨论】:

    标签: pandas list dataframe merge concatenation


    【解决方案1】:

    使用itertools.zip_longestreversed 方法:

    from  itertools import  zip_longest
    a=[1,2,3] 
    b=[2,3]
    
    L = [a, b]
    iterables = (reversed(it) for it in L)
    out = list(reversed(list(zip_longest(*iterables, fillvalue=np.nan))))
    
    df = pd.DataFrame(out, columns=['a','b'])
    print (df)
       a    b
    0  1  NaN
    1  2  2.0
    2  3  3.0
    

    替代方案,如果 b 的值较少,例如 a 列表:

    df = pd.DataFrame(list(zip(a, ([np.nan]*(len(a)-len(b)))+b)), columns=['a','b'])
    print (df)
       a    b
    0  1  NaN
    1  2  2.0
    2  3  3.0
    

    【讨论】:

      【解决方案2】:
      b.append(np.nan)#append NaN
      b=list(set(b))#Use set to rearrange and then return to list
      df=pd.DataFrame(list(zip(a,b)), columns=['a','b'])#dataframe
      
      Alternatively
      b.append(np.nan)#append NaN
      b=list(dict.fromkeys(b))#Use dict to rearrange and return then to list.This creates dict with the items in the list as keys and values as none but in an ordered manner getting NaN to the top
      df=pd.DataFrame(list(zip(a,b)), columns=['a','b'])#dataframe
      

      【讨论】:

        猜你喜欢
        • 2018-12-27
        • 2018-12-02
        • 2020-04-10
        • 1970-01-01
        • 2021-09-19
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多