如何在我的数据框架中插入新的列和sum(),并进行增加、减少notif

2024-06-24 11:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据帧(熊猫中的df)如下:

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)

Tags: 数据dfgreenredsumsectorincreasedecrease
2条回答

可以按样式和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)

如果需要输出列中的绝对值,请添加^{}

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['increase▲/decrease▼'] = (df['Income januari 2019'] - df['Income Januari 2018']).apply(lambda x: '%s ▲' % x if x > 0 else '%s ▼' % -x)

产出将如预期的那样。你知道吗

相关问题 更多 >