Trying to add looped string to empty dataframe pandas

Viewed 68

I am trying to generate links using a for loop and trying to add them to my empty dataframe like the example below:

linkdf = pd.DataFrame(columns=['Link'])


for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  linkdf = linkdf.append(l)

but I am getting errors like below:

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

is there a way to add this to the empty dataframe with header already provided.

want result like below:

        Link
0.  https://google.com/assets/1
1   https://google.com/assets/2
2.  https://google.com/assets/3

Appreciate any help Thanks

2 Answers

First create list and then pass to DataFrame like:

L = ['https://google.com/assets/' + str(i) for i in range(1,10)]
linkdf = pd.DataFrame(L,  columns=['Link'])

Your solution:

L = []
for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  L.append(l)


print (L)
['https://google.com/assets/1', 'https://google.com/assets/2', 
 'https://google.com/assets/3', 'https://google.com/assets/4',  
 'https://google.com/assets/5', 'https://google.com/assets/6', 
 'https://google.com/assets/7', 'https://google.com/assets/8', 
 'https://google.com/assets/9']

linkdf = pd.DataFrame(L,  columns=['Link'])
print (linkdf)
                          Link
0  https://google.com/assets/1
1  https://google.com/assets/2
2  https://google.com/assets/3
3  https://google.com/assets/4
4  https://google.com/assets/5
5  https://google.com/assets/6
6  https://google.com/assets/7
7  https://google.com/assets/8
8  https://google.com/assets/9

If really need add data to empty DataFrame (it is slow):

linkdf = pd.DataFrame(columns=['Link'])

for i in range(1,10):
  l = 'https://google.com/assets/' + str(i)
  linkdf = linkdf.append({'Link':l}, ignore_index=True)

Or why not just np.char.add:

linkdf['Link'] = np.char.add('https://google.com/assets/', np.arange(1, 10).astype(str))

>>> linkdf
                          Link
0  https://google.com/assets/1
1  https://google.com/assets/2
2  https://google.com/assets/3
3  https://google.com/assets/4
4  https://google.com/assets/5
5  https://google.com/assets/6
6  https://google.com/assets/7
7  https://google.com/assets/8
8  https://google.com/assets/9
>>> 
Related