代码之家  ›  专栏  ›  技术社区  ›  yatu Sayali Sonawane

数据帧到一系列列表

  •  -1
  • yatu Sayali Sonawane  · 技术社区  · 6 年前

    假设我有以下数据帧:

    df =pd.DataFrame({'col1':[5,'',2], 'col2':['','',1], 'col3':[9,'','']})  
    print(df)
    
    col1 col2 col3
           5    9
     1               
     2     2    1     
    

    有什么简单的方法可以把它变成 pd.Series 列表,避免空元素?所以:

    0 [5,9]
    1 [1]
    2 [2,2,1]
    
    5 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    使用带有移除空值的列表理解:

    L = [x[x != ''].tolist() for i, x in df.T.items()]
    s = pd.Series(L, index=df.index)
    

    或将值转换为列表 to_dict 带参数 split :

    L = df.to_dict(orient='split')['data']
    print (L)
    [[5, '', 9], ['', '', ''], [2, 1, '']]
    

    然后删除空值:

    s = pd.Series([[y for y in x if y != ''] for x in L], index=df.index)
    
    print (s)
    0    [5, 9]
    1        []
    2    [2, 1]
    dtype: object
    
        2
  •  3
  •   Mayank Porwal    6 年前

    您可以尝试使用 df.values

    拿着就行了 df.values . 将它们转换为列表并使用 map 以下内容:

    In [2193]: df
    Out[2193]: 
      col1 col2 col3
    0         5    9
    1    1          
    2    2    2    1
    

    一班轮:

    In [2186]: pd.Series(df.values.tolist()).map(lambda row: [x for x in row if x != ''])
    Out[2186]: 
    0       [5, 9]
    1          [1]
    2    [2, 2, 1]
    dtype: object
    
        3
  •  2
  •   jpp    6 年前

    类似 @jezreal's solution . 但如果你不期望 0 价值观,你可以使用内在的 False -空字符串的数量:

    L = [x[x.astype(bool)].tolist() for i, x in df.T.items()]
    res = pd.Series(L, index=df.index)
    
        4
  •  2
  •   ayorgo    6 年前

    可以按如下方式进行:

    # Break down into list of tuples
    records = df.to_records().tolist()
    
    # Convert tuples into lists
    series = pd.Series(records).map(list)
    
    # Get rid of empty strings
    series.map(lambda row: list(filter(lambda x: x != '', row)))
    
    # ... alternatively
    series.map(lambda row: [x for x in row if x != ''])
    

    导致

    0    [0, 5, 9]
    1          [1]
    2    [2, 2, 1]
    
        5
  •  1
  •   Caio Belfort    6 年前

    你可以用这个

    In[1]: [x[x.apply(lambda k: k != '')].tolist() for i, x in df.iterrows()]
    
    Out[1]: [[5, 9], [], [2, 1]]