如何在excel中存储python脚本的aws-athena输出?

2024-06-02 10:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python脚本和pyathena库从aws-athena查询,并以表的形式获得正确的输出。你知道吗

Output

现在的问题是我想把输出存储在excel中。你知道吗

有人能建议我,用python脚本如何在Excel中存储输出吗?你知道吗

以下是我在aws athena中用于查询的代码:

from pyathena import connect
import os
import pandas as pd
%matplotlib inline

conn = connect(aws_access_key_id='*****',
                 aws_secret_access_key='*****',
                 s3_staging_dir='s3://****/',
                 region_name='us-west-1')

cursor = conn.cursor()
%time cursor.execute("SELECT * from my_table;")

提前谢谢。。。你知道吗


Tags: keyfromimport脚本awsoutputs3access
1条回答
网友
1楼 · 发布于 2024-06-02 10:33:15

输出到Excel并不局限于创建xlsx文件,您还可以将其写入csv并让Excel加载csv文件。你知道吗

可以使用以下方法创建多个图纸:

from pandas import ExcelWriter
def save_xls(list_dfs, dfs_names, xls_path):
    with ExcelWriter(xls_path) as writer:
        for df,name in zip(list_dfs, dfs_names):
            df.to_excel(writer,name)
        writer.save()

然后可以通过数据的一些转换调用函数,例如透视表和偶数颜色:

save_xls(
    (raw.style.format("{:,.0f}"), 
     actual_table.style.format("{:,.0f}"), 
     diff_table.style.applymap(_color_red_or_green).format("{:,.0f}"), 
     ratio_table.style.applymap(_color_red_yellow_or_green).format("{:.3f}")),
    ('Raw',
    'Actuals',
    'Diff',
    'Ratio'),
    results_with_format.xlsx')

例如,根据单元格的值设置三种颜色的格式:

def _color_red_yellow_or_green(val):
    color = 'red' if val > 0.1 else 'yellow' if val > 0.05 else 'green'
    return 'background-color: %s' % color

相关问题 更多 >