微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将负百分比设置为红色,将正百分比设置为绿色?

如何解决如何将负百分比设置为红色,将正百分比设置为绿色?

我有一个使用 API 收集财务数据并将其转换为 ecxel 文件代码。在我的列中,我有考虑到最后一天股票价格变化的数据,我希望 python 用红色写负变化,用绿色写正变化。我知道如何使用它,使用 if/else 语句,但问题是我应该在 if 语句中调用哪个变量。

这是我使用 request.get 函数从 API 附加数据时的部分。

data = requests.get(batch_apu_call_url).json()
for symbol in symbol_string.split(','):

final_dataframe = final_dataframe.append(
        pd.Series(
        [
            data[symbol]['quote']['companyName'],symbol,data[symbol]['quote']['latestPrice'],data[symbol]['quote']['changePercent'],#This is the line thats collects the changes in the stock prices 
            data[symbol]['quote']['marketCap'],'N/A',data[symbol]['quote']['latestTime']
        ],index=my_columns),ignore_index=True,)

她是我想格式化特殊列的部分

change_format = writer.book.add_format(
{
    'num_format': '0.00%','font_color': 'EA1009' if [] < 0 else '2AEA09',#insted of the square brackets I want to put the variabel 
    'bg_color': background_color,'border': 1
}

)

这是python中部分结果的示例:

                          Name Ticker  Stock Price     +/-%     Market Cap
0    Agilent Technologies Inc.      A      127.120  0.01096    38026751371
1  American Airlines Group Inc    AAL       26.301  0.02625    16894821033
2       Advance Auto Parts Inc    AAP      184.060  0.01200    12369889031
3                    Apple Inc   AAPL      125.884 -0.02000  2114224151643
4                   Abbvie Inc   ABBV      109.250 -0.00430   191633606290

Process finished with exit code 0

和 ecxel 中的结果相同。 ecxel 文件今天没有更新,所以数据可能与python 数据不同。 https://i.stack.imgur.com/i9PIz.png

这是我希望它锁定的: https://i.stack.imgur.com/G8xA5.png

解决方法

我找到了解决方案,最好的方法是:

change_format = writer.book.add_format(
    {
        'num_format': '0.00%[Green];-0.00%[Red]','font_color': '','bg_color': background_color,'border': 1
    }
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。