如何插入新列和 sum(),并在我的数据框中增加、减少通知
how to insert new column and sum(), and make increase, decrase notif in my dataframe
我的数据框(df in pandas)如下:
sector Income Januari 2018 Income januari 2019
1 2000 3000
1 7000 1000
我想用 sum() 插入新列
所以我的预期是:
sector Income Januari 2018 Income januari 2019 increase▲/decrease▼
1 2000 3000 1000 ▲ (green)
1 7000 1000 6000 ▼ (red)
尝试使用下面的代码行:
df['increase▲/decrease▼'] = (df['Income januari 2019'] - df['Income Januari 2018']).apply(lambda x: '%s ▲' % x if x > 0 else '%s ▼' % -x)
输出符合预期。
您可以根据样式设置背景颜色,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)
如果在输出列中需要绝对值,请添加 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
我的数据框(df in pandas)如下:
sector Income Januari 2018 Income januari 2019
1 2000 3000
1 7000 1000
我想用 sum() 插入新列
所以我的预期是:
sector Income Januari 2018 Income januari 2019 increase▲/decrease▼
1 2000 3000 1000 ▲ (green)
1 7000 1000 6000 ▼ (red)
尝试使用下面的代码行:
df['increase▲/decrease▼'] = (df['Income januari 2019'] - df['Income Januari 2018']).apply(lambda x: '%s ▲' % x if x > 0 else '%s ▼' % -x)
输出符合预期。
您可以根据样式设置背景颜色,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)
如果在输出列中需要绝对值,请添加 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