这是我的代码。由于要解析的原始数据的内容,我最终得到长度不同的“用户列表”和“推文列表”。将列表作为数据框中的列编写时,我得到 ValueError: arrays must all be same length
。我意识到这一点,但一直在寻找一种解决方法,在较短数组的正确位置打印 0
或 NaN
。有任何想法吗?
import pandas
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('#raw.html'))
chunk = soup.find_all('div', class_='content')
userlist = []
tweetlist = []
for tweet in chunk:
username = tweet.find_all(class_='username js-action-profile-name')
for user in username:
user2 = user.get_text()
userlist.append(user2)
for text in chunk:
tweets = text.find_all(class_='js-tweet-text tweet-text')
for tweet in tweets:
tweet2 = tweet.get_text().encode('utf-8')
tweetlist.append('|'+tweet2)
print len(tweetlist)
print len(userlist)
#MAKE A DATAFRAME WITH THIS
data = {'tweet' : tweetlist, 'user' : userlist}
frame = pandas.DataFrame(data)
print frame
# Export dataframe to csv
frame.to_csv('#parsed.csv', index=False)
最佳答案
我不确定这是否正是您想要的,但无论如何:
d = dict(tweets=tweetlist, users=userlist)
pandas.DataFrame({k : pandas.Series(v) for k, v in d.iteritems()})
关于python - 具有不同长度数组的 Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798504/