列表项到列

2024-05-23 21:12:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4个网址的列表:

['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']

我想构建Pandas数据框架,它应该有Image_1, Image_2, Image_3Image_4作为列名,url作为行值。你知道吗

我的代码:

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) 

正在返回错误:

File "", line 1 https://cache.wihaben.at/mmo/6/297/469/806_-1094197631.jpg ^ SyntaxError: invalid syntax

求值卡在URL中的“:”上,因为它可能将其解析为dict

我还需要一个选项,在列表中删除n个以上的url,并用值构建相应的列。 列为Image_(iterator_value),行为URL值。你知道吗


Tags: httpsimageurlcache列表evalatlist
3条回答

我认为你混淆了eval的用法。它用于运行保存在字符串中的代码。在您的示例中,python尝试将url作为代码运行,这显然不起作用。您将不需要eval。你知道吗

试试这个:

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

你应该把这个网址做成一个字符串。你知道吗

str((advert_image_list[0])

如果URL存储为字符串(正如@Tox所指出的),我对代码没有问题:

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)

相关问题 更多 >