[英]How to do iterations to change dummy variable in multiple columns from 1 to 0 in Python and Pandas?
I have a dataframe that have over 200 columns of dummy variable:我有一个包含 200 多列虚拟变量的数据框:
Row1 Feature1 Feature2 Feature3 Feature4 Feature5
A 0 1 1 1 0
B 0 0 1 1 1
C 1 0 1 0 1
D 0 1 0 1 0
I want to do iteration to separate each feature to create extra 3 dataframes with df1 only contains keep the first feature that=1 as 1 and change all the later columns to 0 and df2 only contains keep the second feature that=1 as 1 and change all the previous and later columns to 0.我想进行迭代以分离每个特征以创建额外的 3 个数据帧,其中 df1 仅包含将第一个特征 = 1 保留为 1 并将所有后面的列更改为 0,而 df2 仅包含将第二个特征 = 1 保留为 1 并更改所有之前和之后的列都为 0。
I have create codes to do it, but I figured there gotta be better ways to do it.我已经创建了代码来做到这一点,但我认为必须有更好的方法来做到这一点。 Please help me with a more efficient way to approach this.
请帮助我用更有效的方法来解决这个问题。 Thank you!
谢谢!
Below is my code:下面是我的代码:
for index, row in hcit1.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
hcit1.loc[index,title2]=0
else:
pass
for index, row in hcit2.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
hcit1.loc[index,title3]=0
hcit1.loc[index,title]=0
else:
pass
for index, row in hcit3.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
if row[title3]==1:
for l in range(k+1,261):
title4="feature"+str(l)
hcit1.loc[index,title4]=0
hcit1.loc[index,title2]=0
hcit1.loc[index,title]=0
else:
pass
for index, row in hcit4.iterrows():
for i in range(1,261):
title="feature"+str(i)
if int(row[title])==1:
for j in range(i+1,261):
title2="feature"+str(j)
if row[title2]==1:
for k in range(j+1,261):
title3="feature"+str(k)
if row[title3]==1:
for l in range(k+1,261):
title4="feature"+str(l)
if row[title4]==1:
for m in range(l+1,261):
title5="feature"+str(m)
hcit1.loc[index,title5]=0
hcit1.loc[index,title3]=0
hcit1.loc[index,title2]=0
hcit1.loc[index,title]=0
else:
pass
Here:这里:
df1 = df[df['Feature1'] == 1]
df1.iloc[:, :] = 0
df1.loc[:, 'Feature1'] = 1
df2 = df[df['Feature2'] == 1]
df2.iloc[:, :] = 0
df2.loc[:, 'Feature2'] = 1
df3 = df[df['Feature2'] == 1]
df3.iloc[:, :] = 0
df3.loc[:, 'Feature3'] = 1
That should be what you are looking for.那应该是你正在寻找的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.