【问题标题】:Flattening a list of lists, replacing empty sublists with a certain value扁平化列表列表,用特定值替换空子列表
【发布时间】:2020-03-31 13:57:45
【问题描述】:

我有一个列表列表,其中包含空子列表和非空子列表的混合。 列表总长度为240。

_remain = [['24'],
 ['24'],
 ['17'],
 [],
 ['17'],
 [],
 ['17'],...]

我已经尝试将列表列表扁平化为一个列表:

[name for sublist in _remain for name in sublist]

但是当我这样做时,我得到一个长度为 220 的列表。空的子列表消失了。

我的愿望是得到一个扁平列表,用np.nan 替换空列表,以便我可以将它插入熊猫DataFrame

我想得到的结果列表:

['24',
 '24',
 'np.nan',
 '17',
 'np.nan',
 '17',...]

我应该尝试什么?

【问题讨论】:

    标签: python pandas list list-comprehension


    【解决方案1】:

    您可以执行以下操作:

    >>> [name for sublist in _remain for name in (sublist or [np.nan])]
    ['24', '17', nan, '17', nan, '17']
    

    【讨论】:

      【解决方案2】:

      由于 pandas 被标记(尽管可以按照上述答案的建议使用 vanilla python 来完成),一种方法是:

      pd.DataFrame(l).fillna(np.nan).squeeze().tolist()
      

      ['24', '17', nan, '17', nan, '17']
      

      【讨论】:

        【解决方案3】:

        这是一种选择:

        L = [
            ['24'],
            ['17'],
            [],
            ['17'],
            [],
            ['17']
        ]
        L = np.array([l[0] if l else np.nan for l in L])
        

        输出:

        L >> ['24' '17' 'nan' '17' 'nan' '17']
        

        【讨论】:

          【解决方案4】:

          你可以使用一个小的辅助函数:

          lst = [[1], [], [2], [], [3]]
          
          def func(x):
              try:
                  return x[0]
              except IndexError:
                  return None
          
          [func(i) for i in lst]
          # [1, None, 2, None, 3]
          

          【讨论】:

            【解决方案5】:

            你可以用这个:

             flat_list = [item for sublist in l for item in sublist]
            

            flat_list = []
            for sublist in l:
                if len(sublist) == 0:
                    flat_list.append(np.nan)
                else:
                    for item in sublist:
                        flat_list.append(item)
            

            【讨论】:

            • 它放了两个版本,一个处理nan,另一个不处理
            猜你喜欢
            • 2016-01-14
            • 2012-07-01
            • 2019-11-29
            • 2017-09-24
            • 2010-12-13
            • 2017-02-27
            • 2021-03-06
            • 1970-01-01
            相关资源
            最近更新 更多