熊猫:如果 A 列中的行包含字符串 "x", "y" , "z" ,写 " "x_", "y_" , "z_" 到 B 列中的行



对于熊猫,我正在寻找一种方法,根据 A 列中相应行的子字符串将条件值写入 B 列中的每一行。

因此,如果 A 中的单元格包含"WMEAS",请将"MEASURED"写为 B。或者,如果 A 中的单元格包含"WRES",则将"残余"写入 B,或者如果 A 中的单元格包含"WPRES",则将"百分比"写入 B,

我尝试将 str.contains 方法与地图一起使用。正如我所提到的,使用Map,我可以使用两个变量,这是真的,假的,但不是所有四个变量。

create_table['Field_Type'] = create_table ['Field_Type'].map({True: 'Measured', False: 'Estimated'})```

Desired Output :

Field_Name    Field_Type
WMEAS_LD(1)   Measured
RMEAS_LD(1)    Measured
W_LD(1)        Estimated
WPRES_LN(1)    Percentage
WRES_UN(1)      Residual.

[![This is how dataset look like][1]][1]

[1]: https://i.stack.imgur.com/qaRQm.png

您可以遍历"A"的列,然后使用 df.at[] 设置"B"的值

for index, row in df.iterrows():
if(df.at[index,'A'] == "WMEAS"):
df.at[index,'B'] = "Measured"
elif other conditions  
and operations

您可以迭代查找所需的所有组合

def apply_func(col_a):
if "WMEAS" in col_a:
result = "MEASURED"
elif "WRES" in col_a:
result = "Residue"
elif "WPRES" in col_a:
result = "Percentage"
else:
result = ""
return result
df['B'] = df['A'].astype(str).apply(apply_func)

相关内容

最新更新