python - 将 numpy 数组保存到 csv 会产生不匹配错误

标签 python arrays csv numpy tweepy

我正在从 Twitter 收集一堆推文并将其保存到列表中,然后将列表转换为 numpy 数组并尝试将其保存到 CSV 文件。

但是,当我尝试这样做时,出现以下错误:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1215, in savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: a float is required

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 66, in <module>
    main("Trump")
  File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 20, in main
    collect_tweets(api, query)
  File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 54, in collect_tweets
    save_to_csv(tweets_array)
  File "/home/keva161/Documents/Projects/Twitter Sentiment/main.py", line 62, in save_to_csv
    np.savetxt('test.csv', tweets_array)
  File "/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py", line 1219, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U144') and format specifier ('%.18e %.18e %.18e %.18e %.18e %.18e %.18e')

下面是我的代码:

def collect_tweets(api, query):

    tweets_array = []

    public_tweets = api.search(q=query, count=10)

    print("Collecting tweets...")

    for tweet in public_tweets:

        userid = api.get_user(tweet.user.id)
        username = userid.screen_name

        location = tweet.user.location

        tweetText = tweet.text

        analysis = TextBlob(tweet.text)
        polarity = analysis.sentiment.polarity

        datestamp = tweet.created_at
        time = datestamp.strftime("%H:%M")
        year = datestamp.strftime("%d-%m-%Y")

        if (not tweet.retweeted) and ('RT @' not in tweet.text):
            retweet = "Yes"
        else:
            retweet = "No"

        tweets_array.append([username, location, tweetText, retweet, time, year, polarity])

    print("Done!")
    save_to_csv(tweets_array)

def save_to_csv(tweets_array):
    print('Saving to CSV')

    new_array = np.array(tweets_array)
    #headers = ['Username', 'Location', 'Tweet', 'Retweeted', 'Time', 'Year', 'Polarity']
    #np.savetxt("test_file.csv", new_array.flatten(), delimiter=",", fmt='%s')
    np.savetxt('test.csv', tweets_array)

最佳答案

重新访问 np.savetxt 的文档。您可以使用 fmt 参数指定每个数组列或整行使用的格式。默认值假设您要保存 float 数组。

默认的fmt是一种通用的浮点格式,由数组中的列数复制。显然您的数组有七列:'%.18e %.18e %.18e %.18e %.18e %.18e %.18e'。

但错误表明至少其中一列(也许整个数组)包含字符串,而不是数字。错误中的 dtype '

fmt='%s' 应该让您写入此数组。但检查一下结果。它可能需要一些调整。

您注释掉了使用此格式的行:

np.savetxt("test_file.csv", new_array.flatten(), delimiter=",", fmt='%s')

这有什么问题吗?

savetxt 不是一个复杂的函数。它只是迭代数组,并将每个“行”写入文件:

for row in your_array:
    fh.write(asbytes(format % tuple(row) + newline))

其中 format%.18e 的长字符串或根据 fmt 参数构造的内容。

savetxt 在保存二维数值数组时最有意义。对于字符串数组或复合数据类型(结构化),定义有用的格式会更加困难。

关于python - 将 numpy 数组保存到 csv 会产生不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43418010/

相关文章:

python - 将字典列表转换为 CSV

python - 每次调用时都会出现 Scapy AttributeError : 'module' object has no attribute '*'

python - PyCharm SciView 未正确显示数据帧

php - 如何在 PHP 中构建多维数组

Java队列固定大小的数据结构

mysql - JetBrains DataGrip中如何将CSV数据导入MySQL

python - csv.DictReader 给出意想不到的结果

python - NDB 异步 API 和 get_or_insert_async

python - 如何在 Django 中创建随机 slug

javascript - 随机化数组以激活函数