我有一个具有如下通用结构的 DataFrame:
60 700 701 702
0 1 40 40 1
1 40 40 1 10000
2 15 40 40 10000
3 1 40 40 10000
有更多的列(编号从 1 到 1500 左右)和行,但这抓住了本质。我有一个 col_list,在这个例子中col_list= [700, 701, 702]
。现在,如果满足以下条件,我想将某些字段设置为值 1:
所以结果应该是这样的:
60 700 701 702
0 1 40 40 1
1 40 40 1 10000
2 15 1 1 10000
3 1 1 1 10000
我找到了一种笨拙的方法来使用 iterrows,但我真的希望有一种更有效和 Pythonic 的方法。
IUC:
尝试通过loc
,isin()
和replace()
:
m=df[example].isin([10000,40]).all(1)
df.loc[m,example]=df.loc[m,example].replace(40,1)
注意:如果列的类型为字符串,请确保列的类型为 int,然后使用:
df.columns=[int(x) for x in df]
#df.columns=[int(x) if str(x).isnumeric() else x for x in df.columns]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句