如何在Pandas DataFrame中新增差值列并添加增减状态标识
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:
| sector | Income Januari 2018 | Income januari 2019 | increase▲/decrease▼ |
|---|---|---|---|
| 1 | 2000 | 3000 | 1000 ▲ (green) |
| 1 | 7000 | 1000 | 6000 ▼ (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

