我正在尝试从DataFrame B中的列的值中减去DataFrame A中的列的值,但前提是多个列值彼此相等。
假设(虚构的):
DataFrame A:
Index Department Speciality TargetMonth Capacity
1 Sales Cars 2019-1 150
2 Sales Cars 2019-2 120
3 Sales Furniture 2019-1 110
4 IT Servers 2019-1 100
DataFrame B:
Index Department Speciality TargetMonth Required
1 Sales Cars 2019-1 100
2 Sales Cars 2019-2 120
3 IT Servers 2019-1 50
4 Sales Furniture 2019-1 50我故意调换了DataFrame B中索引3和索引4的顺序,而不是A。我的目标是从DataFrame A的capacity列中减去DataFrame B的Required列作为所需的容量小时数,得到另一个不一定需要排序的列表:
Index Department Speciality TargetMonth Result
1 Sales Cars 2019-1 50
2 Sales Cars 2019-2 0
3 Sales Furniture 2019-1 60
4 IT Servers 2019-1 50因此,从技术上讲,只有在所有列值相互匹配而不是基于顺序的情况下才进行减法,因为一个列表或另一个列表中可能缺少一些行。
我可以用一些for循环和条件来解决这个问题,但我想有一个干净整洁的熊猫方法可以用.subtract来解决这个问题,尽管这是我目前被困在其中的“加入”部分。
提前感谢您的宝贵时间。
发布于 2019-02-06 02:31:46
这就是为什么Index如此有用,减法将在索引(行和列)上对齐。
dfA = dfA.set_index(['Department', 'Speciality', 'TargetMonth'])
dfB = dfB.set_index(['Department', 'Speciality', 'TargetMonth'])
dfA.sub(dfB.rename(columns={'Required': 'Capacity'}), fill_value=0)
Capacity
Department Speciality TargetMonth
IT Servers 2019-1 50
Sales Cars 2019-1 50
2019-2 0
Furniture 2019-1 60发布于 2019-02-06 02:39:28
我将使用带有键的合并:
对于此解决方案,将数据帧A作为dfA,将数据帧作为dfB
df_result = pd.merge(dfA, dfB, how='inner', on=['Department','Speciality','TargetMonth'])这将根据关键字“部门”、“专业”、“TargetMonth”将数据帧放在一起,并将产生一个数据帧,其中关键字出现在两个数据帧中(how =“inner”)。
即,如果在dfB中有一个密钥,即:
{'Department': 'IT','Speciality':'Furniture','TargetMonth':2019-1}该值不会出现在dataframe df_result中。更多信息可在此处找到- https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html
然后使用Pandas矢量化的解决方案:
df_result['Result'] = df_result['Capacity'] - df_result['Required']https://stackoverflow.com/questions/54540704
复制相似问题