【问题标题】:Removing square brackets from Dataframe [duplicate]从Dataframe中删除方括号[重复]
【发布时间】:2018-04-12 06:08:01
【问题描述】:

我有以下数据框格式的 adtaset,我需要从数据中删除方括号。我们该如何继续,谁能帮忙

   From             TO
   [wrestle]        engage in a wrestling match
   [write]          communicate or express by writing
   [write]          publish
   [spell]          write
   [compose]        write music

预期输出是:

   From             TO
   wrestle      engage in a wrestling match
   write       communicate or express by writing
   write       publish
   spell       write

【问题讨论】:

    标签: python pandas replace


    【解决方案1】:

    如果strings 使用str.strip

    print (type(df.loc[0, 'From']))
    <class 'str'>
    
    df['From'] = df['From'].str.strip('[]')
    

    ...如果lists 将它们转换为str.join:

    print (type(df.loc[0, 'From']))
    <class 'list'>
    
    df['From'] = df['From'].str.join(', ')
    

    感谢@juanpa.arrivillaga 的建议,如果有一个项目lists:

    df['From'] = df['From'].str[0]
    

    什么是可能的检查方式:

    print (type(df.loc[0, 'From']))
    <class 'list'>
    
    print (df['From'].str.len().eq(1).all())
    True
    

    print (df)
          From                                 TO
    0  wrestle        engage in a wrestling match
    1    write  communicate or express by writing
    2    write                            publish
    3    spell                              write
    4  compose                        write music
    

    【讨论】:

    • 如果确实所有lists 都有一个值,也可以使用df.From.str[0]
    • @juanpa.arrivillaga - 谢谢你的建议。
    • @jezrael 我有一个问题,是否可以将df['From'] = df['From'].str.strip('[]') 应用于整个数据框,而无需逐列单独执行?
    • @1muflon1- 是的,使用this
    【解决方案2】:

    假设你有这个数据框:

    df = pd.DataFrame({'Region':['New York','Los Angeles','Chicago'], 'State': ['NY [new york]', '[California]', 'IL']})
    

    会是这样的:

            Region          State
    0     New York  NY [new york]
    1  Los Angeles   [California]
    2      Chicago             IL
    

    要删除方括号,您需要以下几行:

    df['State'] = df['State'].str.replace(r"\[","")
    df['State'] = df['State'].str.replace(r"\]","")
    

    结果:

            Region        State
    0     New York  NY new york
    1  Los Angeles   California
    2      Chicago           IL
    

    如果你想删除它们之间的所有东西的方括号:

    df['State'] = df['State'].str.replace(r"\[.*\]","")
    df['State'] = df['State'].str.replace(r" \[.*\]","")
    

    第一行只是删除方括号之间的字符,第二行考虑字符前的空格,所以为了确保安全,最好同时运行这两行。

    通过在原始df上应用这两行:

            Region State
    0     New York    NY
    1  Los Angeles      
    2      Chicago    IL
    

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 2019-12-30
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      相关资源
      最近更新 更多