python - 具有不同长度数组的 Pandas

标签 python arrays pandas dataframe

这是我的代码。由于要解析的原始数据的内容,我最终得到长度不同的“用户列表”和“推文列表”。将列表作为数据框中的列编写时,我得到 ValueError: arrays must all be same length。我意识到这一点,但一直在寻找一种解决方法,在较短数组的正确位置打印 0NaN。有任何想法吗?

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/

相关文章:

python - Matplotlib 在动画刷新后连接数据末尾

python - 如何仅在 Pandas 数据框的选定行和列上应用函数?

c - 使用 C 中的 realloc() 函数增加二维数组中的列

C# 将数组类型的对象转换为 T,其中 T 是数组?

python - 将文本读入数据框

Python pandas 从字符串中删除子字符串之后的部分

python - Panda dataframe groupby 和回归计算

c++ - 从 boost python 调用具有可变数量输入参数的 Python 函数

用于从 Azure Key Vault 读取 secret 的 Python 脚本

C++ 即使发生错误也删除数组