0

I have a huge df (720 columns) with this structure:

id A B C
1  1 0 1
2  1 0 1 
3  1 1 1

I would like to create a new df, based on calculations such as:

if A and B = 1 then  v1 = 1
if A and C = 1 then  v2 = 1
if A and D = 1 then  v3 = 1
if A and XX = 1 then v719 = 1

id V1 V2 
1  0  1
2  0  1 
3  1  1

As I need to iterate A vs B and C (in reality A vs 719 columns) I looking for a way to write this code without doing something like this for ALL columns

df.loc[((df['A'] == 1) & (df['B'] == 1)), 'v1'] = 1
df.loc[((df['A'] == 1) & (df['C'] == 1)), 'v2'] = 1
df.loc[((df['C'] == 1) & (df['D'] == 1)), 'v2'] = 1
df.loc[((df['A'] == 1) & (df['XX'] == 1)), 'v719'] = 1

Any ideas?

1 Answer 1

3

For your question we can do , since 1 * 1 = 1

s=df.loc[:,'B':].mul(df.A,axis=0)
   B  C
0  0  1
1  0  1
2  1  1
s.columns=np.arange(s.shape[1])+1
df=df.join(s.add_prefix('v_'))
Sign up to request clarification or add additional context in comments.

6 Comments

Maybe I've oversimplified. Actually conditions are more like: if A = 1 and B = 2 then v1 = 1 etc...
@EGM8686 Is it two for all columns or just B?
Tricky part is that is for ALL columns. So in this case I end up with 3 dfs (A with B, A with C and B with C)
Sorry, I meant the values. B =2, C =2 or would C = 3 being it's the third column.
@EGM8686 The provided solution in only multiplying against A, but you want all combinations. I searched around and I think this should get you going: stackoverflow.com/questions/29229892/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.