[英]Python pandas dataframe skipping lines
所以我有這個循環,將字符串添加到數據幀。 這很好。 但是,當我嘗試在第二列中添加數字時,它會跳過行(如您在輸出中看到的那樣)。而counter <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。
pd.DataFrame.append
每次pd.DataFrame.append
追加一行。 您可以在字典中包含2個鍵,以便為每次迭代添加一行:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.