iyya
iyya

Reputation: 43

replace values in dictionary python

i have 2 dictionary named ch_jaman and cdf950

ch jaman
{'Ancolmekar': array([0. , 0. , 0. , ..., 0. , 0. , 0.5]),
'Cidurian': array([0., 0., 0., ..., 0., 0., 0.]),
'Dayeuhkolot': array([0., 0., 0., ..., 0., 0., 0.]),
'Hantap': array([0., 0., 0., ..., 0., 0., 0.]),
'Kertasari': array([0., 0., 0., ..., 0., 0., 0.]),
'Meteolembang': array([0., 0., 0., ..., 0., 0., 0.]),
'Sapan': array([0., 0., 0., ..., 0., 0., 0.])}
cdf950
{'Ancolmekar': 15.5,
 'Cidurian': 18.5,
 'Dayeuhkolot': 5.5,
 'Hantap': 14.0,
 'Kertasari': 11.5,
 'Meteolembang': 11.5,
 'Sapan': 15.0}

i want to obtain biner 1,0 with condition. and this is my code that not yet working

for stas in ch_jaman:
    for j in enumerate(ch_jaman):
        if ch_jaman[stas]>=cdf950[stas]:
            ch_jaman[j][stas] = 1
        elif ch_jaman[stas]<cdf950[stas]:
            ch_jaman[j][stas] = 0

and there was an error like this ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

what should i do. please help . thank you

Upvotes: 0

Views: 564

Answers (1)

EnMag
EnMag

Reputation: 83

It appears that ch_jaman is a dictionary from strings to list of numbers, while cdf950 maps strings into numbers.

Therefore, the expression ch_jaman[stas]>=cdf950[stas] is trying to compare a list of numbers with a number. What is your goal here? Do you want to compare each element of the array ch_jaman[stas] with the number cdf950[stas]?

In addition, what happens if cdf950 does not contain an entry for the key stas?

Assuming you want to replace every number in the array with 1 or 0 depending on whether the value is greater or less than the corresponding value in cdf950 a possible solution could be the following:

for key, ch_vals in ch_jaman.items():
    if key in cdf950:
        ch_jaman[key] = [1 if val >= cdf950[key] else 0 for val in ch_vals]
    else:
        ch_jaman[key] = [-1] * len(ch_vals)

where I insert -1 if the key is in ch_jaman but not in cdf950.

Upvotes: 2

Related Questions