Home > Mobile >  How do I create list of URL strings using a dataframe/series of values?
How do I create list of URL strings using a dataframe/series of values?

Time:04-06

I have a series of values IDs that I convert to a dataframe dfA that outputs as:

IDs
0 ID_3456789065
1 ID_4546567657
2 ID_1765768878

I'm trying to convert dfA['IDs'] into a string list of URLs that outputs as:

'https://api.names.io/v1/ids/ID_3456789065/IDAccounts'
'https://api.names.io/v1/ids/ID_4546567657/IDAccounts'
'https://api.names.io/v1/ids/ID_1765768878/IDAccounts'

This gets me what I want if I manually enter an ID:

acctID = 'ID_3456789065'
f'https://api.names.io/v1/ids/{acctID}/IDAccounts'

Outputs:

'https://api.names.io/v1/ids/ID_3456789065/IDAccounts'

I keep getting the wrong output or an error when I try looping through dfA using different versions of this:

urlList=[]

for i in dfA:
  acctID = dfA[i]
  urlList = f'https://api.names.io/v1/ids/{acctID}/IDAccounts'
  urlList.append(urlList)

Outputs:

https://api.names.io/v1/ids/0    ID_3456789065
1    ID_4546567657
2    ID_1765768878
Name: data_bettor, dtype: object/IDAccounts

I've tried .concat too and that throws TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

Please help!

CodePudding user response:

You could use a list comprehension that iterates over the "IDs" column:

out = [f'https://api.names.io/v1/ids/{acctID}/IDAccounts' for acctID in df['IDs']]

Output:

['https://api.names.io/v1/ids/ID_3456789065/IDAccounts',
 'https://api.names.io/v1/ids/ID_4546567657/IDAccounts',
 'https://api.names.io/v1/ids/ID_1765768878/IDAccounts']

CodePudding user response:

You can use:

urlList = list('https://api.names.io/v1/ids/'   df['IDs']   '/IDAccounts')
print(urlList)

# Output
['https://api.names.io/v1/ids/ID_3456789065/IDAccounts',
 'https://api.names.io/v1/ids/ID_4546567657/IDAccounts',
 'https://api.names.io/v1/ids/ID_1765768878/IDAccounts']

CodePudding user response:

You can use apply() on the IDs column and use to_list to get a list out of the series:

 df["IDs"].apply(lambda acctID: f'https://api.names.io/v1/ids/{acctID}/IDAccounts').to_list()

This outputs:

['https://api.names.io/v1/ids/ID_3456789065/IDAccounts',
 'https://api.names.io/v1/ids/ID_4546567657/IDAccounts',
 'https://api.names.io/v1/ids/ID_1765768878/IDAccounts']
  • Related