【问题标题】:Dataframe slicing from cell after reading csv读取 csv 后从单元格中切片的数据框
【发布时间】:2018-11-12 23:44:51
【问题描述】:

我正在使用 CSV 和 DataFrames 从 Twitter 分析中读取数据。

我想从某个单元格中提取网址

输出是这个过程如下

tweet number tweet id               tweet link              tweet text
1            1.0086341313026E+018   "tweet link goes here"  tweet text goes here https://example.com"

我如何分割这个“推文文本”来获取它的网址?我无法使用 [-1:-12] 对其进行切片,因为有许多具有不同字符编号的推文。

【问题讨论】:

    标签: python string python-3.x pandas series


    【解决方案1】:

    我相信你想要:

    print (df['tweet text'].str[-12:-1])
    0    example.com
    Name: tweet text, dtype: object
    

    更通用的解决方案是使用regexstr.findall 作为所有链接的列表,如有必要,首先通过使用str[0] 进行索引来选择:

    pat = r'(?:http|ftp|https)://(?:[\w_-]+(?:(?:\.[\w_-]+)+))(?:[\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?'
    
    print (df['tweet text'].str.findall(pat).str[0])
    0    https://example.com
    Name: tweet text, dtype: object
    

    【讨论】:

    • 这正是我所需要的。谢谢。
    【解决方案2】:

    这是一种使用字符串列表和pd.Series.apply 来查找有效 URL 的方法:

    s = pd.Series(['tweet text goes here https://example.com',
                   'some http://other.com example',
                   'www.thirdexample.com is here'])
    
    test_strings = ['http', 'www']
    
    def url_finder(x):
        return next(i for i in x.split() if any(t in i for t in test_strings))
    
    res = s.apply(url_finder)
    
    print(res)
    
    0     https://example.com
    1        http://other.com
    2    www.thirdexample.com
    dtype: object
    

    【讨论】:

      【解决方案3】:

      如果域名长度是可变的,而不是总是 11 个字符长,这是一个可行的替代方案:

      In [2]: df['tweet text'].str.split('//').str[-1]
      
      Out[2]:
      1    example.com
      Name: tweet text, dtype: object
      

      【讨论】:

      • 更好的是df['tweet text'].str.split('//').str[-1])
      • 谢谢,认为一定有比申请更好的方法,但找不到,将编辑。
      猜你喜欢
      • 2022-01-21
      • 2019-05-07
      • 2018-11-16
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 2020-12-31
      • 2014-03-04
      • 2020-01-28
      相关资源
      最近更新 更多