首页 文章

数据帧到系列列表

提问于
浏览
-1

假设我有以下数据帧:

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 回答

  • 1

    可以这样做:

    # 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]
    
  • 1

    你可以用它

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

    您可以尝试使用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

    @jezreal's solution相似 . 但是,如果您不希望 0 值,则可以使用空字符串的固有 False -ness:

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

    使用list comprehension删除空值:

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

    或者通过参数 splitto_dict的值转换为列表:

    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
    

相关问题