I want to create a new column then use another parameter as a condition to populate that column.
Here is my code how ever it doest continue to elif. Only the first argument is applying even though it did not meet the parameter I set.
for i in df_csrdata_2mos_Filtered_Done["Agent"]:
if i == "unez" or i == "rmbua" or i == "destrada" or i == "amateo" or i == "cmabelison":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 1"
elif i == "rverga" or i == "dpcaban" or i == "dgsugui":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 2"
elif i == "gmic" or i == "jdera":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 3"
elif i == "gras" or i == "mcsrra":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 4"
elif i == "jcawan" or i == "rmcola" or i == "mjgamo":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 5"
elif i == "ychaco" or i == "phondra":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 6"
elif i == "mmorang" or i == "vsin":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 7"
elif i == "pbong":
df_csrdata_2mos_Filtered_Done["AgentTag"] = "Agent 8"
else:
print("AgentTag Done!")
CodePudding user response:
Your if/elif is working fine.
Based on df_
I'll assume you're working with Pandas dataframes, and in that case it's just that df_csrdata_2mos_Filtered_Done["AgentTag"] = "X"
replaces the whole series with a new value.
>>> df = pd.DataFrame({"a": [1, 2, 3]})
>>> df
a
0 1
1 2
2 3
>>> df["b"] = "Agent Perry"
>>> df
a b
0 1 Agent Perry
1 2 Agent Perry
2 3 Agent Perry
>>>
If the last Agent
would be "pbong"
, all of the AgentTags in the df would be Agent 8.
It looks like all in all you're looking for Series.map()
with a dict:
>>> agent_map = {
... "unez": "Agent 1",
... "rverga": "Agent 2",
... }
>>> df = pd.DataFrame({"agent": ["unez", "rverga", "hello"]})
>>> df
agent
0 unez
1 rverga
2 hello
>>> df["AgentTag"] = df["agent"].map(agent_map)
>>> df
agent AgentTag
0 unez Agent 1
1 rverga Agent 2
2 hello NaN
>>>
CodePudding user response:
Dont use loops, here not necessary.
Better is mapping by Series.map
:
d = {
"Agent 1": ["unez", "rmbua", "destrada", "amateo", "cmabelison"],
"Agent 2": ["rverga", "dpcaban", "dgsugui"],
"Agent 3": ["gmic", "jdera"],
"Agent 4": ["gras", "mcsrra"],
"Agent 5": ["jcawan", "rmcola", "mjgamo"],
"Agent 6": ["ychaco", "phondra"],
"Agent 7": ["mmorang", "vsin"],
"Agent 8": ["pbong"],
}
# flatten lists
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
df_csrdata_2mos_Filtered_Done["AgentTag"] = df_csrdata_2mos_Filtered_Done["Agent"].map(d1)