如何检查数据框单元格是否包含值,然后根据条件填充字段
How check if a dataframe cell includes the values and then populate field based on condition
我有一个数据框列,其值如下:
Column_1(String are present in a cell with space in between)
ABC DEF EFG HIJ
ZCG VHT UIO QAR
ABC KLM MNO STU
DEF KLM ABD EFG
我需要根据条件填充值:
if Column_1 includes ABC and not KLM then 1
if Column_1 includes KLM and not ABC then 2
if Column_1 includes both ABC and KLM then 3
if Column_1 does not include both ABC and KLM then 4
SO Column_1 变为:
Column_1
1
4
3
2
尝试:
mapper = {
(True, False): 1,
(False, True): 2,
(True, True): 3,
(False, False): 4,
}
df["Value"] = df["Column_1"].apply(lambda x: mapper[("ABC" in x, "KLM" in x)])
print(df)
打印:
Column_1 Value
0 ABC DEF EFG HIJ 1
1 ZCG VHT UIO QAR 4
2 ABC KLM MNO STU 3
3 DEF KLM ABD EFG 2
我有一个数据框列,其值如下:
Column_1(String are present in a cell with space in between)
ABC DEF EFG HIJ
ZCG VHT UIO QAR
ABC KLM MNO STU
DEF KLM ABD EFG
我需要根据条件填充值:
if Column_1 includes ABC and not KLM then 1
if Column_1 includes KLM and not ABC then 2
if Column_1 includes both ABC and KLM then 3
if Column_1 does not include both ABC and KLM then 4
SO Column_1 变为:
Column_1
1
4
3
2
尝试:
mapper = {
(True, False): 1,
(False, True): 2,
(True, True): 3,
(False, False): 4,
}
df["Value"] = df["Column_1"].apply(lambda x: mapper[("ABC" in x, "KLM" in x)])
print(df)
打印:
Column_1 Value
0 ABC DEF EFG HIJ 1
1 ZCG VHT UIO QAR 4
2 ABC KLM MNO STU 3
3 DEF KLM ABD EFG 2