Skip to content

Instantly share code, notes, and snippets.

@mwestwood
Created May 11, 2023 16:13
Show Gist options
  • Save mwestwood/8763028359db5975ac7993dcbcf320d0 to your computer and use it in GitHub Desktop.
Save mwestwood/8763028359db5975ac7993dcbcf320d0 to your computer and use it in GitHub Desktop.
import pandas as pd
import numpy as np
# Example data for last week and this week values
last_week = [0, 10, 0, 30, 40, 0]
this_week = [10, 20, 30, 40, 50, 60]
# Create a pandas DataFrame
df = pd.DataFrame({'Last Week': last_week, 'This Week': this_week})
# Conditionally adjust the values
mask = df['Last Week'] == 0
df.loc[mask, 'Last Week'] = 1
df.loc[mask, 'This Week'] += 1
# Calculate the percent change
df['Percent Change'] = (df['This Week'] - df['Last Week']) / df['Last Week'] * 100
df['Percent Change'] = np.where(df['Last Week'] == 0, df['This Week'] * 100, df['Percent Change'])
# Display the DataFrame
print(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment