Load entire dict into a particular dataframe cell


Load entire dict into a particular dataframe cell


df =
columnA columnAB
row1 xxx
row2 yyy
row3 zzz
row4 xyx

expected df =
columnA columnAB columnB
row1 xxx [('A1(80)', ['BB11', 'A11', 'A21']), ('B1(70)', ['CC55', 'HH21']), ('C1(60)', ['KK88'])]
row2 yyy
row3 zzz
row4 xyx

from collections import defaultdict

d1, d2 = defaultdict(int), defaultdict(list)

d = {'A1BB11': 10,
'B1CC55': 20,
'A1A11': 30,
'A1A21': 40,
'B1HH21': 50,
'C1KK88': 60
}

for k, v in d.items():
prefix = k[:2]
d1[prefix] += v
d2[prefix].append(k[2:])

final = {'{}({})'.format(k, d1[k]): v for k, v in d2.items()}

print(final)
# {'A1(80)': ['BB11', 'A11', 'A21'],
# 'B1(70)': ['CC55', 'HH21'],
# 'C1(60)': ['KK88']}



Now I need to load this data in a dataframe cell, I tried converting this into list and load


final = sorted(final.items())
# type(final) = <class 'list'>

df.loc[df['columnA'].str.contains('row1', na=False), 'columnB'] = final



But I run into error
ValueError: setting an array element with a sequence



could you suggest a way to handle this





what's your df structure? Also, post the final expected result
– RomanPerekhrest
Jun 29 at 18:42



df





updated the problem statement with df and expected df
– Rahul
Jun 29 at 19:14




1 Answer
1



Assuming columnB is already an exiting column of the dataframe, try this:


columnB


df.loc[df['columnA'].str.contains('row1', na=False), ['columnB']] =
df.loc[df['columnA'].str.contains('row1', na=False), ['columnB']].applymap(lambda x: final)



if columnB doesn't exit, reindex the dataframe before applymap as:


columnB


applymap


df = df.reindex(columns=['columnA', 'columnAB', 'columnB'], fill_value='')



or insert it with empty value


df['columnB'] = ''





Just reindex the dataframe before applymap, I updated the answer
– xhamr
Jun 29 at 20:41


applymap





It says series object has no Attribute applymap
– Rahul
Jun 29 at 20:59





It throws following error, AttributeError: 'Series' object has no attribute 'applymap'
– Rahul
Jun 29 at 21:10






Sorry, i forgot the brackets around 'columnB', check the updated answer
– xhamr
Jun 29 at 22:12






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV