如何将 numpy 数组作为 csv 写入 S3

问题描述

我有一个带有 2 列的 numpy ndarray,如下所示

[[1.8238497e+03 5.2642276e-06]
 [2.7092224e+03 6.7980350e-06]
 [2.3406370e+03 6.6842499e-06]
 ...
 [1.7234612e+03 6.6842499e-06]
 [2.1071147e+03 2.1332115e-05]
 [2.6937273e+03 6.2854801e-06]]

我想使用 s3fs 将它直接写为带有列名的 csv 列在 S3 中(不创建本地 csv 文件)。如果我有数据框并且可以将 numpy 转换为数据框,我知道该怎么做。但我想要一种无需将 numpy 数组转换为数据帧的方法

下面是我的代码

output = [[1.8238497e+03 5.2642276e-06]
     [2.7092224e+03 6.7980350e-06]
     [2.3406370e+03 6.6842499e-06]
     ...
     [1.7234612e+03 6.6842499e-06]
     [2.1071147e+03 2.1332115e-05]
     [2.6937273e+03 6.2854801e-06]]
## write the outpout in csv at s3
s3 = s3fs.S3FileSystem(anon=False)
dftowrite = pd.DataFrame({'col1': output[:,0],'col2': output[:,1]})

with s3.open(f"{'s3://bucket'}/result.csv",'w') as f:
     dftowrite.to_csv(f)

我想在不将 NumPy 数组 output 转换为数据帧 dftowrite 的情况下执行此操作。有什么建议吗?

解决方法

试试这个

game_state = False
@bot.event
async def on_message(message):
    global game_state

    # Don't do anything if the message is from the bot
    if message.author == bot.user:
        return


    if message.content.startswith("$Hi"):
        await message.channel.send("Hello")


    # WOULD YOU RATHER GAME COMMANDS


    if message.content.startswith("$WYRG"):
        await message.channel.send(random.choice(ListOfWYRGQuestions) + "\n\n Please enter 1 or 2 for option 1 or option 2.")
        game_state = True
    if message.content.startswith("1") and game_state:
        await message.channel.send("Good choice!")
        game_state = False
    elif message.content.startswith("2") and game_state:
        await message.channel.send("Good Choice!")
        game_state = False