【问题标题】:Extracting string between special characters in a csv column在csv列中的特殊字符之间提取字符串
【发布时间】:2017-11-10 16:02:52
【问题描述】:

我想从转推中提取用户句柄,即;之间的任何用户名 “RT @username:xyzxyzxyz” 到一个新列。我做了以下

df = pd.read_csv("string.csv")
for index,row in df.iterrows(): 
    df['Influencers'] = df['Tweet'].str.extract("\(@*?)\:")
df.to_csv('string3.csv', index=False)

它产生了以下错误:

  File "C:\ANACONDA\lib\re.py", line 251, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis

样本 DF:

df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})

【问题讨论】:

    标签: python regex csv pandas


    【解决方案1】:

    试试这个:

    df = pd.read_csv("string.csv")
    df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False)
    

    更新:

    In [34]: df
    Out[34]:
                            Tweet
    0      RT @username:xyzxyzxyz
    1         Free text RT @user2
    2                 Blah - blah
    3  Text @another_user:aaaaaaa
    
    In [35]: df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False).fillna('Original')
    
    In [36]: df
    Out[36]:
                            Tweet Influencers
    0      RT @username:xyzxyzxyz   @username
    1         Free text RT @user2      @user2
    2                 Blah - blah    Original
    3  Text @another_user:aaaaaaa    Original
    

    【讨论】:

    • @lightyagami96,请extend your question 提供一个小的可重复数据集和所需的数据集。请阅读how to make good reproducible pandas examples并相应地编辑您的帖子。
    • 感谢您的建议,df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})
    • @lightyagami96 也可以随意投票给 MaxU 的答案。你现在有 >= 15 代表
    • @lightyagami96,很高兴我能帮上忙 :)
    【解决方案2】:

    对不起,我解决了这个问题,但我无法针对上述情况实现 else 条件:

    df = pd.read_csv("string.csv")
    for index,row in df.iterrows(): 
        if "RT @" in row["Tweet"]: 
            df['Influencers'] = "@"+df['Tweet'].str.extract("\@(.+?)\:", expand= False)
        else :
            df['Influencers'] = "Original"
    df.to_csv('string3.csv', index=False)
    

    它为 else 条件生成空白行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2017-09-02
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多