0

I have a code which checks to see whether a column contains a list and if found it will explode that list and convert the exploded column into int if it is numeric. However, I ran into a problem as some lists in my file contains dictionaries. How would I include that into my existing code to check whether the list contains a dictionary/keys, and if so, it should not explode that column and leave it as it is.

Current Code:

x = (doc.applymap(type) == list).all()
y = x.index[x].tolist()
for i in y:
    doc= doc.explode(i)
    if (doc[i].str.isnumeric().all()) == True:
        x = (doc[i].to_frame().columns)
        doc[x] = doc[x].fillna(0).astype(int)

Input:

ID

"number": [1,2,3,4],
"number": [{"enabled": 1,2,3,4}]

Expected Output

ID
1
2
3
4
[{"enabled": 1,2,3,4}]
jcoke
  • 1,555
  • 1
  • 13
  • 27
  • Does this answer your question? [How to check if a variable is a dictionary in Python?](https://stackoverflow.com/questions/25231989/how-to-check-if-a-variable-is-a-dictionary-in-python) – Mike Scotty Feb 15 '21 at 13:01
  • That question is slightly different, its checking to see whether its a dictionary, my one is checking to see whether a dictionary is actually inside the list – jcoke Feb 15 '21 at 13:03
  • 2
    Then iterate all your list items and check each one if it's a dict or not? You can stop checking once you've found a dict. – Mike Scotty Feb 15 '21 at 13:05
  • so you want to know whether you're exploding a dictionary or list right? just have a two step check then? in any case, can you provide a sample of your data ? – Umar.H Feb 15 '21 at 13:07
  • I've included an idea of how the input is and what the output should be like, so yes there should be a two step check, check to see if the column contains a list which I have done, but then check to see if that list contains a dictionary, if it does then print it however it is, if it doesnt contain a dictionary then explode the column – jcoke Feb 15 '21 at 13:28

2 Answers2

0

Might not be the best way but this does the job:

for i in y:
    m = str(doc[i][0]).strip('[]')
    if m[0] == '{' and m[-1] == '}':
        pass
    else:
        doc = doc.explode(i)
        if (doc[i].str.isnumeric().all()) == True:
            x = (doc[i].to_frame().columns)
            doc[x] = doc[x].fillna(0).astype(int)
jcoke
  • 1,555
  • 1
  • 13
  • 27
0

I'm not completely sure what you are trying to do but this is how you can check if a dict is in a list.

The upper one only returns True or False if the list contains a dict, the second one gives you the item itself.

mylist = [1, 2, 3,{"key":"value"} 4, 5]
if any(type(x) is dict for x in mylist):
    #List contains a dict
else:
    #do other stuff


for x in mylist:
    item_type = type(x)
    if(item_type is dict):
        #item is dict
    else:
        #item is not dict

Rik02
  • 36
  • 4