【问题标题】:duplicating rows by splitting comma separated multiple values in another column pandas通过在另一列熊猫中拆分逗号分隔的多个值来复制行
【发布时间】:2021-03-03 03:38:27
【问题描述】:

我从NameError: name 'Series' is not defined找到了应该可以工作的代码

但我收到一个错误“名称'系列'未定义”。它在示例中运行良好,但其他用户也出现了此错误。有谁知道如何让它工作?

任何帮助将不胜感激!

original_df = DataFrame([{'country': 'a', 'title': 'title1'},
               {'country': 'a,b,c', 'title': 'title2'},
               {'country': 'd,e,f', 'title': 'title3'},
               {'country': 'e', 'title': 'title4'}])

desired_df = DataFrame([{'country': 'a', 'title': 'title1'},
               {'country': 'a', 'title': 'title2'},
               {'country': 'b', 'title': 'title2'},
               {'country': 'c', 'title': 'title2'},
               {'country': 'd', 'title': 'title3'},
               {'country': 'e', 'title': 'title3'},
               {'country': 'f', 'title': 'title3'},
               {'country': 'e', 'title': 'title4'}])

#Code I used:
desired_df = pd.concat(
    [
        Series(row["title"], row["country"].split(","))
        for _, row in original_df.iterrows()
    ]
).reset_index()

【问题讨论】:

    标签: python pandas rows comma


    【解决方案1】:

    首先split 逗号上的列得到一个列表,然后你可以explode 那个系列的列表。将'title' 移动到索引,以便为'country' 中的每个元素重复它。最后两部分只是清理名称并从索引中删除标题。

    (df.set_index('title')['country']
       .str.split(',')
       .explode()
       .rename('country')
       .reset_index())
    

        title country
    0  title1       a
    1  title2       a
    2  title2       b
    3  title2       c
    4  title3       d
    5  title3       e
    6  title3       f
    7  title4       e
    


    此外,您的原始代码在逻辑上没有问题,但您需要正确创建对象。我建议导入模块而不是单独的类/方法,因此您可以使用 pd.Series 而不是 Series 创建一个 Series

    import pandas as pd
                    
    desired_df = pd.concat([pd.Series(row['title'], row['country'].split(','))              
                            for _, row in original_df.iterrows()]).reset_index()
    

    【讨论】:

      【解决方案2】:

      您可以在此处使用pd.Series.str.splitdf.explode

      df['country'] = df['country'].str.split(',')
      df.explode('country').reset_index(drop=True)
      
        country   title
      0       a  title1
      1       a  title2
      2       b  title2
      3       c  title2
      4       d  title3
      5       e  title3
      6       f  title3
      7       e  title4
      

      对于NameError,您可以使用这种方式导入。

      from pandas import DataFrame, Series
      

      注意:使用上述导入语句只会将DataFrameSeries 类带入作用域。

      【讨论】:

      • 谢谢,Ch3steR!这也是一个很好的解决方案。如果有更多列,并且需要在新的 df(例如 df_countries)中查看所有列,则可以使用以下代码... df['country'] = df['country'].str。 split(',') df_countries = ( df.explode('country') .reset_index(drop=False) )
      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2021-02-02
      • 2014-07-02
      • 2021-10-13
      • 2022-01-18
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多