我有一个巨大的df(720列),其结构如下:
id A B C
1 1 0 1
2 1 0 1
3 1 1 1
我想基于以下计算来创建新的df:
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
因为我需要迭代A与B和C(实际上是A与719列),所以我在寻找一种编写此代码的方法,而无需对所有列进行此类操作
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
有什么想法吗?
答案 0 :(得分:3)
对于您的问题,我们可以做到,因为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_'))