I have a dataframe df with the columns delta and integer_id. I have a dict d that maps integer_id to some floating point value. I want to divide each row's delta in df by the corresponding value from d for the integer_id, and if the row's integer_id doesn't exist in the dict, leave delta unchanged.
Here's an example:
df = pd.DataFrame({
"integer_id": [1, 2, 3],
"delta": [10, 20, 30]
})
d = {1: 0.5, 3: 0.25}
The result should be
df = pd.DataFrame({
"integer_id": [1, 2, 3],
"delta": [20, 20, 120] # note the middle element is unchanged
})
I tried df["delta"] /= df.integer_id.map(d), but this will return NaN for the second row because d doesn't have the corresponding key. But something like
df["delta"] /= df.integer_id.map(lambda x: d.get(x, 1))
will get what I need, but I'm wondering what other approaches there are for this case?
source https://stackoverflow.com/questions/77545270/how-to-divide-column-in-dataframe-by-values-in-a-dict-according-to-some-key
Comments
Post a Comment