Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting many URLs in a python dataframe

I have a dataframe which contains text including one or more URL(s) :

user_id          text
  1              blabla... http://amazon.com ...blabla
  1              blabla... http://nasa.com ...blabla
  2              blabla... https://google.com ...blabla ...https://yahoo.com ...blabla
  2              blabla... https://fnac.com ...blabla ...
  3              blabla....

I want to transform this dataframe with the count of URL(s) per user-id :

 user_id          count_URL
    1               2 
    2               3
    3               0

Is there a simple way to perform this task in Python ?

My code start :

URL = pd.DataFrame(columns=['A','B','C','D','E','F','G'])

for i in range(data.shape[0]) :
  for j in range(0,8):
     URL.iloc[i,j] = re.findall("(?P<url>https?://[^\s]+)", str(data.iloc[i]))

Thanks you

Lionel

like image 275
Krukiou Avatar asked Aug 03 '26 04:08

Krukiou


1 Answers

In general, the definition of a URL is much more complex than what you have in your example. Unless you are sure you have very simple URLs, you should look up a good pattern.

import re
URLPATTERN = r'(https?://\S+)' # Lousy, but...

First, extract the URLs from each string and count them:

df['urlcount'] = df.text.apply(lambda x: re.findall(URLPATTERN, x)).str.len()

Next, group the counts by user id:

df.groupby('user_id').sum()['urlcount']
#user_id
#1    2
#2    3
#3    0
like image 51
DYZ Avatar answered Aug 05 '26 18:08

DYZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!