【问题标题】:Pandas: list of lists to expanded rowsPandas:展开行的列表列表
【发布时间】:2018-07-07 12:21:56
【问题描述】:

我有这个question 的扩展名。我的列中有列表列表,我需要进一步扩展行。如果我只是重复这些步骤,它会将我的字符串分成字母。你能建议一个聪明的方法吗?谢谢!

d1 = pd.DataFrame({'column1': [['ana','bob',[1,2,3]],['dona','elf',[4,5,6]],['gear','hope',[7,8,9]]],
                   'column2':[10,20,30],
                  'column3':[44,55,66]})

d2 = pd.DataFrame.from_records(d1.column1.tolist()).stack().reset_index(level=1, drop=True).rename('column1')

d1_d2 = d1.drop('column1', axis=1).join(d2).reset_index(drop=True)[['column1','column2', 'column3']]

d1_d2

【问题讨论】:

  • 预期输出是什么?

标签: python-3.x pandas


【解决方案1】:

看来你需要flatten嵌套lists:

from collections import Iterable

def flatten(coll):
    for i in coll:
            if isinstance(i, Iterable) and not isinstance(i, str):
                for subc in flatten(i):
                    yield subc
            else:
                yield i

d1['column1'] = d1['column1'].apply(lambda x: list(flatten(x)))
print (d1)
                 column1  column2  column3
0    [ana, bob, 1, 2, 3]       10       44
1   [dona, elf, 4, 5, 6]       20       55
2  [gear, hope, 7, 8, 9]       30       66

然后使用您的解决方案:

d2 = (pd.DataFrame(d1.column1.tolist())
        .stack()
        .reset_index(level=1, drop=True)
        .rename('column1'))

d1_d2 = (d1.drop('column1', axis=1)
          .join(d2)
          .reset_index(drop=True)[['column1','column2', 'column3']])

print (d1_d2)
   column1  column2  column3
0      ana       10       44
1      bob       10       44
2        1       10       44
3        2       10       44
4        3       10       44
5     dona       20       55
6      elf       20       55
7        4       20       55
8        5       20       55
9        6       20       55
10    gear       30       66
11    hope       30       66
12       7       30       66
13       8       30       66
14       9       30       66

【讨论】:

    【解决方案2】:

    假设预期结果与 jezrael 相同。

    熊猫 >= 0.25.0

    d1 = d1.explode('column1').explode('column1').reset_index(drop=True)
    

    d1:

       column1  column2  column3
    0      ana       10       44
    1      bob       10       44
    2        1       10       44
    3        2       10       44
    4        3       10       44
    5     dona       20       55
    6      elf       20       55
    7        4       20       55
    8        5       20       55
    9        6       20       55
    10    gear       30       66
    11    hope       30       66
    12       7       30       66
    13       8       30       66
    14       9       30       66
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多