因此,我有一个循环,它向dataframe添加一个字符串。这个很好用。但是,当我试图在第二列中添加一个数字时,它跳过了行(正如您在输出中看到的那样).`,而计数器< 50:
#gets just the subreddit name
e = str(elem[counter].get_attribute("href"))
e = e.replace("https://www.reddit.com/r/", "")
e = e[:-1]
#e is the subreddit string
df = df.append({'Subreddit': e}, ignore_index=True)
df = df.append({'Appearances': 1 }, ignore_index=True)
print(e)
counter = counter + 2
print(df)`产出-
Subreddit Appearances
0 worldnews NaN
1 NaN 1
2 pics NaN
3 NaN 1
4 aww NaN
5 NaN 1
6 RedditInReddit NaN我知道这与我的循环方式有关,但我似乎无法理解。另外,我必须每次增加2次,因为subreddits在页面上出现了两次,而我只需要抓取1。
发布于 2018-10-05 00:47:56
pd.DataFrame.append每次追加一行。您可以在字典中包含两个键,以便为每次迭代添加一行:
df = df.append({'Subreddit': e, 'Appearances': 1}, ignore_index=True)但是,您不应该以这种方式在循环中使用pd.DataFrame.append。这将是低效的,因为由于额外的复制操作,pd.DataFrame.append比list.append昂贵。
相反,您可以构建一个列表并调用pd.DataFrame.append一次。下面是一些伪代码:
L = []
for _ in some_iterable:
L.append([e, 1])
to_append = pd.DataFrame(L, columns=['Subreddit', 'Appearances'])
df = df.append(to_append, ignore_index=True)https://stackoverflow.com/questions/52656862
复制相似问题