[英]transform specific column value based on condition and update another row with that transformed value
I have a dataframe that looks something like: 我有一个类似于以下内容的数据框:
Obj_1 Obj_2 Obj_3 Num_1 Num_2 Num_3 Month
A BCD QW 111 222 3456 2018-12
B Bdfh AQW 1114 1222 23456 2018-12
A BCD QW 22222 67 3463 2019-01
B Bdfh AQW 15511 2422 13456 2019-01
A BCD QW 257 457867 34663 2019-02
B Bdfh AQW 11551 27722 53456 2019-02
.....
.....
....
I would like to apply some basic math computation such that if Obj_3 == 'AQW' and Month == '2018-12', then pick the corresponding Num_3 value and multiply by 2, and assign that to the row that corresponds to 2019-02 with the same Obj columns combinations. 我想应用一些基本的数学计算,如果Obj_3 =='AQW'和月=='2018-12',则选择相应的Num_3值并乘以2,并将其分配给对应于2019-的行 - 02具有相同的Obj列组合。
So the output would look something like : 所以输出看起来像:
Obj_1 Obj_2 Obj_3 Num_1 Num_2 Num_3_adj Month
A BCD QW 111 222 3456 2018-12
B Bdfh AQW 1114 1222 23456 2018-12
A BCD QW 22222 67 3463 2019-01
B Bdfh AQW 15511 2422 13456 2019-01
A BCD QW 257 457867 34663 2019-02
B Bdfh AQW 11551 27722 46912 2019-02
.....
.....
....
I am thinking of first ordering the dataframe by object columns, then assign a flag or counter to unique object row combinations. 我想首先按对象列排序数据帧,然后为唯一对象行组合分配一个标志或计数器。 Post that filter for the condition and assign it to a row where the counter matches and the Month matches the desired type.
发布该条件的过滤器并将其分配给计数器匹配的行,并且Month与所需类型匹配。
You can achieve the expected output with the following code, 您可以使用以下代码实现预期输出,
>>> df.loc[df.query('Obj_3 == "AQW" and Month == "2019-02"').index,'Num_3']=df.query('Obj_3 == "AQW" and Month == "2018-12"')['Num_3'].mul(2).values
>>> df
Obj_1 Obj_2 Obj_3 Num_1 Num_2 Num_3 Month
0 A BCD QW 111 222 3456 2018-12
1 B Bdfh AQW 1114 1222 23456 2018-12
2 A BCD QW 22222 67 3463 2019-01
3 B Bdfh AQW 15511 2422 13456 2019-01
4 A BCD QW 257 457867 34663 2019-02
5 B Bdfh AQW 11551 27722 46912 2019-02
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.