How to apply a function on a series of columns, based on the values in a corresponding series of columns?

Brayton :

I have a df where I have several columns, that, based on the value (1-6) in these columns, I want to assign a value (0-1) to its corresponding column. I can do it on a column by column basis but would like to make it a single function. Below is some example code:

import pandas as pd
df = pd.DataFrame({'col1': [1,3,6,3,5,2], 'col2': [4,5,6,6,1,3], 'col3': [3,6,5,1,1,6],
                  'colA': [0,0,0,0,0,0], 'colB': [0,0,0,0,0,0], 'colC': [0,0,0,0,0,0]})

(col1 corresponds with colA, col2 with colB, col3 with colC)

This code works on a column by column basis:

df.loc[(df.col1 != 1) & (df.col1 < 6), 'colA'] = (df['colA']+ 1)

But I would like to be able to have a list of columns, so to speak, and have it correspond with another. Something like this, (but that actually works):

m = df['col1' : 'col3'] != 1 & df['col1' : 'col3'] < 6
df.loc[m, 'colA' : 'colC'] += 1

Thank You!

jezrael :

Idea is filter both DataFrames by DataFrame.loc, then filter columns by mask and rename columns by another df2 and last use DataFrame.add only for df.columns:

df1 = df.loc[:, 'col1' : 'col3'] 
df2 = df.loc[:, 'colA' : 'colC']

d = dict(zip(df1.columns,df2.columns))

df1 = ((df1 != 1) & (df1 < 6)).rename(columns=d)

df[df2.columns] = df[df2.columns].add(df1)
print (df)
   col1  col2  col3  colA  colB  colC
0     1     4     3     0     1     1
1     3     5     6     1     1     0
2     6     6     5     0     0     1
3     3     6     1     1     0     0
4     5     1     1     1     0     0
5     2     3     6     1     1     0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360171&siteId=1