You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas DataFrame中新增差值列并添加增减状态标识

Solution for Adding Color-Coded Income Difference Column in Pandas

Got it, let's break down how to achieve exactly what you need—adding a calculated difference column with color-coded increase/decrease indicators. Here's a step-by-step solution:

Step 1: Setup Your Sample DataFrame (for testing)

First, let's recreate your DataFrame to ensure we're working with the same dataset:

import pandas as pd

data = {
    'sector': [1, 1],
    'Income Januari 2018': [2000, 7000],
    'Income januari 2019': [3000, 1000]
}
df = pd.DataFrame(data)

Step 2: Calculate the Income Difference

We'll first compute the raw difference between 2019 and 2018 income. Pay close attention to the case difference in your column names (Januari vs januari)—we need to match them exactly to avoid key errors:

# Calculate difference: 2019 income minus 2018 income
df['difference'] = df['Income januari 2019'] - df['Income Januari 2018']

Step 3: Define a Formatting Function for Color & Symbols

To get the colored up/down indicators, we'll use Pandas' Styler API (this works in Jupyter Notebooks, Colab, or any environment that renders HTML). Define a function to style each cell based on the difference value:

def format_diff(val):
    abs_value = abs(val)
    if val > 0:
        # Positive difference = increase (green bold text + ▲)
        return f'color: green; font-weight: bold; {abs_value} ▲'
    elif val < 0:
        # Negative difference = decrease (red bold text + ▼)
        return f'color: red; font-weight: bold; {abs_value} ▼'
    else:
        # No change
        return '0 -'

Step 4: Apply Styling & Rename the Column

Now we'll apply the formatting to our difference column, rename it to your desired header, and render the styled DataFrame:

# Apply styling, rename the column, and prepare for display
styled_df = df.style.format(
    {'increase▲/decrease▼': format_diff}
).rename(columns={'difference': 'increase▲/decrease▼'})

# Show the result (in HTML-rendering environments, this displays colored text)
styled_df

Expected Output

In a supported environment, your output will match exactly what you requested:

sectorIncome Januari 2018Income januari 2019increase▲/decrease▼
1200030001000 ▲ (green)
1700010006000 ▼ (red)

Note: If you're working in a terminal/console that doesn't support HTML, the color won't render, but the numbers and symbols will still display correctly.

内容的提问来源于stack exchange,提问作者Charisma Bathara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:41:09