Reputation: 15182
I have list with 4 urls:
['https://cache.wihaben.at/mmo/6/297/469/806_-1094197631.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_-455156804.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_466214286.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_1475201828.jpg']
and I want to build Pandas dataframe which should have Image_1, Image_2, Image_3
andImage_4
as column names and URLs as row values.
My code:
advert_images = {('Image_1', eval(advert_image_list[0])),
('Image_2', eval(advert_image_list[1])),
('Image_3', eval(advert_image_list[2])),
('Image_4', eval(advert_image_list[3])),
}
adIm_DF = pd.DataFrame(advert_images)
is returning error:
File "", line 1 https://cache.wihaben.at/mmo/6/297/469/806_-1094197631.jpg ^ SyntaxError: invalid syntax
Evaluation is stuck on ":
" in URL because it's probably parsing it as dict.
I also need option to itterate over n-number of URLs in list and build coresponding columns with values.
Columns being Image_(iterator_value)
, row being URL
value.
Upvotes: 0
Views: 76
Reputation: 2600
If the URls are stored as a string (as @Tox pointed out) I have no problem with the code:
url_list = ['https://cache.wihaben.at/mmo/6/297/469/806_-1094197631.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_-455156804.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_466214286.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_1475201828.jpg']
im_labels = ['Image_{}'.format(x) for x in np.arange(1, len(url_list) ,1)]
im_df = pd.DataFrame([url_list], columns=im_labels)
Upvotes: 2
Reputation: 3770
this works for me
df = pd.DataFrame(columns=['Image1','Image2','Image3','Image4'])
df.loc[0] = ['https://cache.wihaben.at/mmo/6/297/469/806_-1094197631.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_-455156804.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_466214286.jpg', 'https://cache.wihaben.at/mmo/6/297/469/806_1475201828.jpg']
Upvotes: 1
Reputation: 2267
I think you are confusing the use of eval
. It is used to run code that is saved in a string. In your example python tries to run the url as code, which will obviously not work. You will not need eval
.
Try this:
advert_image_list = ['https://cache.willhaben.at/mmo/6/297/469/806_-1094197631.jpg', 'https://cache.willhaben.at/mmo/6/297/469/806_-455156804.jpg', 'https://cache.willhaben.at/mmo/6/297/469/806_466214286.jpg', 'https://cache.willhaben.at/mmo/6/297/469/806_1475201828.jpg']
advert_images = [('Image_1', advert_image_list[0]),
('Image_2', advert_image_list[1]),
('Image_3', advert_image_list[2]),
('Image_4', advert_image_list[3])]
adIm_DF = pd.DataFrame(advert_images).set_index(0).T
Upvotes: 1