Skip to main content
 首页 » 编程设计

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

2024年10月01日7shanyou

我正在从 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 在保存二维数字数组时最有意义。使用字符串数组或复合数据类型(结构化),很难定义有用的 format。