i've data frame(df in pandas) below:
sector Income Januari 2018 Income januari 2019
1 2000 3000
1 7000 1000
and i want to insert new column with sum()
so my expected:
sector Income Januari 2018 Income januari 2019 increase▲/decrease▼
1 2000 3000 1000 ▲ (green)
1 7000 1000 6000 ▼ (red)
You can set background color by styles and export to excel:
def color(x):
c1 = 'background-color: green'
c2 = 'background-color: red'
c = ''
m = x['Income januari 2019'] > x['Income Januari 2018']
df1 = pd.DataFrame(c, index=x.index, columns=x.columns)
df1['increase▲/decrease▼'] = np.where(m, c1, c2)
return df1
df['increase▲/decrease▼'] = df['Income januari 2019'] - df['Income Januari 2018']
print (df)
sector Income Januari 2018 Income januari 2019 increase▲/decrease▼
0 1 2000 3000 1000
1 1 7000 1000 -6000
df.style.apply(color,axis=None).to_excel('styled.xlsx', engine='openpyxl', index=False)
If need absolute values in output column add Series.abs
:
df['increase▲/decrease▼'] = (df['Income januari 2019'] - df['Income Januari 2018']).abs()
print (df)
sector Income Januari 2018 Income januari 2019 increase▲/decrease▼
0 1 2000 3000 1000
1 1 7000 1000 6000