Reputation: 2024
I have a dictionary that's something like this.
d = {
"p1": ["$0.00", nan, "$25.00"],
"p2": ["$30.25", nan, "$12.25"],
"p3": ["$0.00"],
"p4": [nan, "$15.00"]
}
I'd like to look up values from the dictionary and assign them to a column in pandas DataFrame. The DataFrame is something like this:
df = pd.DataFrame({
'name': ["p1","p2","p3","p4"],
'val': [np.nan, np.nan, 4, np.nan]
})
Assignment:
def fun(name):
# look up from dict
# apply condition
return
df['val'] = df.apply(lambda x: func(x['name']), axis=1)
For the assignment, the condition is to find the largest value from the dictionary, if length of the value pair > 0, i.e there is more than 1 element in the list. Note, the elements are stored as strings. So, need the function needs to convert them to float type.
Expected output:
Upvotes: 1
Views: 1259
Reputation: 261900
First rework your dictionary to keep the "highest" value with a custom key
. Then perform a simple map
:
d2 = {k: max((e for e in v if pd.notna(e)),
key=lambda x: float(x.strip('$')) if isinstance(x, str) else x)
for k,v in d.items()}
# {'p1': '$25.00', 'p2': '$30.25', 'p3': '$0.00', 'p4': '$15.00'}
df['val'] = df['name'].map(d2)
output:
name val
0 p1 $25.00
1 p2 $30.25
2 p3 $0.00
3 p4 $15.00
Upvotes: 1