Why is this for loop on columns [0-15] not working?

Viewed 40

This is my dataset:

0 1 2
{'sequence': 1, 'timingDate': '2022-01-07', 'c... {'sequence': 2, 'category.coding': [{'code' {'sequence': 3, 'category.coding': [{'code':

I am able to do this individually; however, this take a long time. A loop would be more efficient. There is actually 0-15 columns that need to be applied

Essentially this what the loop should do.

one_st = sI[0].apply(pd.Series)
two_st = sI[1].apply(pd.Series)
three_st = sI[2].apply(pd.Series)
# and so on through column 15

This is my code.

sI = pd.json_normalize(df30['supportingInfo'])
for i in range(len(sI)):
    sI[i].apply(pd.Series)

My error is this:

KeyError: 13

1 Answers

First of all, you could apply your function on each column of a dataframe in a single statement:

df = df.apply(pd.Series)  # Also... df.apply(lambda column: pd.Series(column))

Now, the problem with KeyError: 13 means that there's not column with name 13 on your dataframe. You could check the name of your columns by printing the column names:

print(df.columns)  # If you have many columns... print(list(df.columns))

Also, you could just apply your function on the first 15 columns, whatever their name is:

df[df.columns[:15]] = df[df.columns[:15]].apply(pd.Series)
Related