简体   繁体   English

熊猫根据另一列将条件应用于列值

[英]pandas apply condition to column value based on another column

I have a df that looks like the below: 我有一个如下所示的df:

        date   2017-10-07  2017-10-08
id                                                                 
1    2017-09-07      46.0         5.0   
2    2017-10-07       1.0         0.0   
3    2017-11-07     123.0         0.0   
4    2017-10-07       0.0         0.0   
5    2017-10-08       0.0         0.0

and want to be able to lookup the date value from the 'date' column, and if it matches the column name of the columns with date titles, change that specific value in the df. 并希望能够从“日期”列中查找日期值,如果它与带有日期标题的列的列名匹配,请在df中更改该特定值。

For instance, in the df above, the output would look like: 例如,在上面的df中,输出如下所示:

        date   2017-10-07  2017-10-08
id                                                                 
1    2017-09-07      46.0         5.0   
2    2017-10-07       1.0         0.0   
3    2017-11-07     123.0         0.0   
4    2017-10-07   "CHANGED"       0.0   
5    2017-10-08       0.0      "CHANGED"

I can do this in a for loop over each column and row, but it is time consuming and I know there has to be a better way. 我可以在每个列和行的for循环中执行此操作,但这很耗时,我知道必须有更好的方法。

Thanks in advance! 提前致谢!

You can use numpy broadcasting, perform assignment, and reassign the result back. 您可以使用numpy广播,执行分配以及将结果重新分配回去。

v = df.values[:, 1:]
v[df.date.values[:, None] == df.columns[1:].values] = 'CHANGED'
df.iloc[:, 1:] = v

df

          date 2017-10-07 2017-10-08
id                                  
1   2017-09-07         46          5
2   2017-10-07    CHANGED          0
3   2017-11-07        123          0
4   2017-10-07    CHANGED          0
5   2017-10-08          0    CHANGED

By using stack and unstack 通过使用stackunstack

df1=df.reset_index().melt(['id','date'])
df1.loc[df1.date==df1.variable,'value']='changed'
df1.set_index(['id','variable','date']).unstack(-2)
Out[189]: 
                   value           
variable      2017-10-07 2017-10-08
id date                            
1  2017-09-07         46          5
2  2017-10-07    changed          0
3  2017-11-07        123          0
4  2017-10-07    changed          0
5  2017-10-08          0    changed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM