EGM8686
EGM8686

Reputation: 1572

Pandas create multiple columns based on other columns

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?

Upvotes: 0

Views: 71

Answers (1)

BENY
BENY

Reputation: 323396

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_'))

Upvotes: 3

Related Questions