我正在使用 Beautiful Soup 迭代一些 HTML div:
for div in soup.findAll('a', {'class': 'result'}):
adLink = div.a.get('href')
adInfo= {
u'adLink':adLink,
u'adThumbImg':...some code...,
u'adCounty':...some code...
}
adFullInfo = getFullAdInfo(adLink)
adInfo.update(adFullInfo)
ads_CarsURL = pd.DataFrame(data=adInfo) #Create pandas DF
其中 getFullAdInfo
是函数
def getFullAdInfo {
...some code...
}
返回的字典看起来像这样:
{'adID': '2027007',
'adTitle': 'Ford 750 Special',
'adDatePublished': '20.11.2009',
'adTimePublished': '14:23',
'adViewed': '102',
'carPriceEUR': '600',
'carManufacturer': 'Ford'}
因此,在每次迭代中,我都会从 adInfo
字典和 adFullInfo
函数获取值,该函数返回另一个字典并将它们合并,以便我可以拥有单个字典记录。
最后的想法是创建 pandas 数据框。
我得到的错误是:
ValueError: arrays must all be same length
我不知道为什么会这样,当我最初为每个字典键定义所有变量并为它们分配空字符串(如 adID=""
)以防它们丢失时。
最佳答案
获得完整广告后,将其转换为 1 行数据帧,然后将其附加到最终数据帧中。这将解决长度不匹配的问题,以及是否存在可供其他广告使用的广告上不可用的数据。您必须弄清楚逻辑,因为您还没有提供那部分代码来测试。下面是我的意思的简单例子:
import pandas as pd
data1 = {'adID': '2027007',
'adTitle': 'Ford 750 Special',
'adDatePublished': '20.11.2009',
'adTimePublished': '14:23',
'adViewed': '102',
'carPriceEUR': '600',
'carManufacturer': 'Ford'}
data2 = {'adID': '20555',
'adTitle': 'Honda',
'adTimePublished': '11:23',
'adViewed': '2',
'carManufacturer': 'Honda'}
# Initialize empty dataframe
final_df = pd.DataFrame()
# Iterate through your dictionaries, convert to 1 row dataframe and append it to your final dataframe
for data in [data1, data2]:
temp_df = pd.DataFrame(data, index=[0])
final_df = final_df.append(temp_df, sort=True).reset_index(drop=True)
具体来说,根据您提供的内容,它将类似于:
ads_CarsURL = pd.DataFrame()
for div in soup.findAll('a', {'class': 'result'}):
adLink = div.a.get('href')
adInfo= {
u'adLink':adLink,
u'adThumbImg':...some code...,
u'adCounty':...some code...
}
adFullInfo = getFullAdInfo(adLink)
adInfo.update(adFullInfo)
temp_df = pd.DataFrame(adInfo, index=[0])
ads_CarsURL = final_df.append(temp_df, sort=True).reset_index(drop=True)
输出:
print (final_df.to_string())
adDatePublished adID adTimePublished adTitle adViewed carManufacturer carPriceEUR
0 20.11.2009 2027007 14:23 Ford 750 Special 102 Ford 600
1 NaN 20555 11:23 Honda 2 Honda NaN
关于python - 合并 2 个字典并将它们存储在 pandas 数据框中,其中一个字典具有可变长度列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957367/