Reputation: 73
If I have a dictionary like this, which I then assign to a data frame to use for mapping, is there a way to add conditional statements to the mapping so that they only happen if the condition is true?
mapping_pbm = {'Hospice': ['JOURNEY\'S HOSPICE', 'SALMON VALLEY HOSPICE', 'FIRST CHOICE HOSPICE',
'CASTLE HILLS EDGEWOOD'], 'Tag': ['JOURNEYS',
'SALMON VALLEY', 'FIRST CHOICE',
'CASTLE HILLS, HOUSE STOCK']}
pbm_mapping_df = pd.DataFrame(data=mapping_pbm)
p = dict(zip(pbm_mapping_df.Tag, pbm_mapping_df.Hospice))
raw_direct_data['responsible_name'] = raw_direct_data['responsible_name'].map(p)
The above code is from elsewhere in my program, it takes the 'responsible_name' column and renames all the incorrectly named entries to what they should be.
for index in data1f.index:
price = float(data1f.loc[index, 44])
id = data1f.loc[index, 36]
if price > 0 & id != 1234:
if data1f.loc[index, 28] in ("ACH1507", "CE11507", "CE21507", "CE51507", "LHH1507", "BBH1507", "DOC1507"):
if price + 2 < 19.99:
price = 19.99
data1f.loc[index, 44] = price
elif price + 2 > 19.99:
price = price + 2
data1f.loc[index, 44] = price
elif data1f.loc[index, 28] in ("KEY1507", "FCH1507", "SVH1507", "JOU1507"):
price = (price * 1.3) + 2
data1f.loc[index, 44] = price
elif price < 0:
if data1f.loc[index, 28] in ("ACH1507", "CE11507", "CE21507", "CE51507", "LHH1507", "BBH1507", "DOC1507"):
if price - 2 > -19.99:
price = -19.99
data1f.loc[index, 44] = price
elif price - 2 < -19.99:
price = price - 2
data1f.loc[index, 44] = price
elif data1f.loc[index, 28] in ("KEY1507", "FCH1507", "SVH1507", "JOU1507"):
price = (price * 1.3) - 2
data1f.loc[index, 44] = price
This code is what I'm currently using to set the prices in my data for a price plan we're using. Is there a way to combine these two concepts so I don't have to use a for loop/conditional statements?
Example Desired Input/Output
Input:
Hospice | Price |
---|---|
JOURNEYS | 7.99 |
FIRST CHOICE | 19.99 |
SALMON VALLEY | -7.99 |
Output:
Hospice | Price |
---|---|
JOURNEY'S HOSPICE | 19.99 |
FIRST CHOICE HOSPICE | 21.99 |
SALMON VALLEY HOSPICE | -19.99 |
Upvotes: 1
Views: 56
Reputation: 26676
Say input is df.
Map df.Hospice
to a dictionary of pbm_mapping_df['Tag']:pbm_mapping_df['Hospice']
Can create the dictionary using dict(zip(key:value))
df['Hospice']=df['Hospice'].map(dict(zip(pbm_mapping_df['Tag'],pbm_mapping_df['Hospice'])))
Hospice Price
0 JOURNEY'S HOSPICE 7.99
1 FIRST CHOICE HOSPICE 19.99
2 SALMON VALLEY HOSPICE -7.99
Upvotes: 1