gpt4 book ai didi

python - 如何对同一列中的字段进行减法 - Python

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:08 25 4
gpt4 key购买 nike

我有以下初始数据框:

enter image description here

Country      Gender     Q1
Australia M Increase
Australia F Increase
Australia M Increase
Australia M Decrease
India M Decrease
India F Increase
India M Decrease
South Africa F Decrease
UK F Increase

这里我们计算每个过滤器的 Q1:

enter image description here

Country       Gender      Q1         Count(Q1)
Australia M Increase 2
Australia F Increase 1
Australia M Decrease 1
India M Decrease 2
India F Increase 1
South Africa F Decrease 1
UK F Increase 1

现在对于同一个过滤器,我需要减去计数(增加)和计数(减少)ans 存储在 Q1“Net”的新选项中。因此 Net = count(increase) - count(decrease)。最终的数据框看起来像这样:

enter image description here

这在 Python 中可行吗?

问候,

最佳答案

将 default_count 列添加到初始数据框,然后使用 pivot_table

   df=pd.DataFrame({'country':['Australia','Australia','Australia','Australia','India','India','India','South Africa','UK'],'gender':['M','F','M','M','M','F','M','F','F'],'Q1':['Increase','Increase','Increase','Decrease','Decrease','Increase','Decrease','Decrease','Increase'],'default_count':['1','1','1','1','1','1','1','1','1']})

df_pivot=df.pivot_table(index=['country','gender'],columns='Q1',aggfunc='count',values='default_count').reset_index().fillna(0)

df_pivot['Net']=df_pivot['Increase']-df_pivot['Decrease']

关于python - 如何对同一列中的字段进行减法 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com