【问题标题】:Fill array with rows of different lenghts Python用不同长度的Python行填充数组
【发布时间】:2018-07-09 13:29:39
【问题描述】:

所以我发现了这个: Numpy: Fix array with rows of different lengths by filling the empty elements with zeros

但我真正想要的是:

mylist = [[1],[1,2],[1,2,3]]

mylist.fill()
>>> [[0,0,1], [0,1,2], [1,2,3]]

我知道 pandas 的 fillna 填充,但 0 在我的矩阵的右侧,我需要它们在左侧。有什么线索吗?

【问题讨论】:

  • 你有没有试过写一个用零填充的函数?
  • 来自帮助中心:仔细检查您问题的拼写。

标签: python arrays pandas numpy


【解决方案1】:

我认为应该这样做:

def fill(a):
    length = max([len(i) for i in a])
    return [[0]*(length-len(i)) + i for i in a]

fill(mylist)
#[[0,0,1], [0,1,2], [1,2,3]]

【讨论】:

    【解决方案2】:

    既然你标记了pandas

    pd.DataFrame(mylist).\
      apply(lambda x: sorted(x, key=pd.notnull), 1).\
        fillna(0).astype(int).values.tolist()
    Out[89]: [[0, 0, 1], [0, 1, 2], [1, 2, 3]]
    

    【讨论】:

    • 这看起来很有趣。如果您可以添加更多详细信息,那就太好了
    • @GarbageCollector 使用构造函数创建数据框,是否使用 NaN 对每一行进行排序(如果 NaN 移到前面),然后转换回列表
    • @GarbageCollector 它使用键对行元素进行简单排序。
    【解决方案3】:

    用 0 填充并排序值检查它们是否不是 0,即

    df = pd.DataFrame(mylist)
    df.fillna(0).apply(lambda x : sorted(x,key=lambda x : x!=0),1).values.astype(int).tolist()
    
    [[0, 0, 1], [0, 1, 2], [1, 2, 3]]
    

    【讨论】:

    • 也许添加 astype( int ) :-)
    猜你喜欢
    • 2018-05-27
    • 2015-08-30
    • 2017-10-12
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多