pandas 将条件应用于多列以替换

9rbhqvlz  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(157)

我有一个包含以下列的数据框,其中一些IGFRESAS列包含数据,但我将仅根据这些条件替换不存在的数据-参见打印屏幕

我想使用条件EV_EM == 0,然后将EV_RND复制到所有IGFREAS4X列。
我为一个专栏写了这个:

df["IGFREAS41"]=np.where(df['EV_EM'] == 0, df['EV_RND'], df["IGFREAS41"])

我试过这个:列=["IGFREAS41"、"IGFREAS43"、"IGFREAS44"、"IGFREAS42"] NP,其中(df ["EV_EM"]== 0,df ["EV_RND"],df [列])
我得到这个错误:- --〉13个节点,其中(df ["EV_EM"]== 0,df ["EV_RND"],df [列])
文件〈数组函数内部结构〉:180,其中(* args,**kwargs)
ValueError:操作数无法与形状(13,)(13,)(13,4)一起广播

9bfwbjaz

9bfwbjaz1#

如果我正确地理解了这个问题,那么下面的方法是有效的:

import pandas as pd

data={"EV_EM":[0,1,0,0,1,0,0,1,1],
      "EV_RND":["EM Not Avaiable","","EM Not Avaiable1","EM Not Avaiable2","","EM Not Avaiable3","EM Not Avaiable4","",""],
      "IGFREAS41":["","","","","","","","",""],
      "IGFREAS42":["","","","","","","","",""],
      "IGFREAS43":["","","","","","","","",""],
      }
df=pd.DataFrame(data)

mask=df["EV_EM"]==0

cols_to_fill=[x for x in df.columns if x.startswith("IGFREAS")]

df.loc[mask,cols_to_fill]=df["EV_RND"]

相关问题