【问题标题】:iterating through a list with a function that relates list objects使用与列表对象相关的函数遍历列表
【发布时间】:2017-02-12 19:41:41
【问题描述】:

假设我有一个列表:

stuff = ['Dogs[1]','Jerry','Harry','Paul','Cats[1]', 'Toby','Meow','Felix']

是否可以遍历列表并以如下数据框格式将动物名称分配给动物:

Animal    Name
Dog       Jerry
Dog       Harry
Dog       Paul
Cat       Toby... etc

通过遍历列表

for i in stuff:
    if '1' in i:
        new_list.append(i)...

我一直在详尽地搜索如何做到这一点,但找不到任何东西。

【问题讨论】:

    标签: python list pandas iteration


    【解决方案1】:

    我认为你可以先使用DataFrame构造函数:

    df = pd.DataFrame({'Name':stuff})
    print (df)
          Name
    0  Dogs[1]
    1    Jerry
    2    Harry
    3     Paul
    4  Cats[1]
    5     Toby
    6     Meow
    7    Felix
    

    然后DataFrame.insert 新列Animalstr.extract 值与[1] 和最后使用boolean indexingSeries.duplicated 掩码:

    df.insert(0, 'Animal', df['Name'].str.extract('(.*)\[1\]', expand=False).ffill())
    df = df[df['Animal'].duplicated()].reset_index(drop=True)
    print (df)
      Animal   Name
    0   Dogs  Jerry
    1   Dogs  Harry
    2   Dogs   Paul
    3   Cats   Toby
    4   Cats   Meow
    5   Cats  Felix
    

    str.contains创建的另一种可能的掩码解决方案

    df.insert(0, 'Animal', df['Name'].str.extract('(.*)\[1]', expand=False).ffill())
    df = df[~df['Name'].str.contains('\[1]')].reset_index(drop=True)
    print (df)
      Animal   Name
    0   Dogs  Jerry
    1   Dogs  Harry
    2   Dogs   Paul
    3   Cats   Toby
    4   Cats   Meow
    5   Cats  Felix
    

    【讨论】:

    • 很好的答案。谢谢。
    【解决方案2】:

    您可以从字典列表构建数据框。所以像

    dicts = []
    animal = ""
    for i in stuff:
        if '1' in i:
            animal = i[:-3]
        else:
            dicts.append({'Name': i, 'Animal': animal}
    pd.DataFrame(dicts)
    

    不过,这个(以及我能想象到的任何其他解决方案)确实很脆弱。您最好确定输入的格式。

    【讨论】:

      猜你喜欢
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2011-08-19
      • 2018-05-08
      • 2015-03-17
      • 2011-06-11
      相关资源
      最近更新 更多