1

Im reading a SQL query with pd.read_sql().

One of the columns of the query has array type, but Pandas doesn't recognize this as an array, but as a string.

How do I change de type of the column to be able to iterate over its values?

This is the df head:

        main_ID                      related_ids
1      00088381096959               [PRDKQUOV2JAR17RD, PRDKPYH11Z4GFZOV]
2       0011509002051               [PRCOFOK9MJ2CTABE, PRSESJD2K7PFYVUM]
3       0011509002051               [OSPAA89FNMJH9UWK, OSPW2JJQ949ZHNS3]
4       0019954960568               [PRDORZT50BDS1Z6H, PRDHG07MVG1YCX2N]

Then I will need to do something like this:

for item,row in df.iterrows():
    for id in row['related_ids']:
         code...

1 Answer 1

1

TRY:

via strip() and split():

df['related_ids']=df['related_ids'].str.strip('[]').str.split(',')

OR

If you need np.array() then use:

df['related_ids']=df['related_ids'].str.strip('[]').str.split(',').map(np.array)
Sign up to request clarification or add additional context in comments.

1 Comment

with pd.eval() show this error pandas.core.computation.ops.UndefinedVariableError: name 'OSPRSPQK33EAY22L' is not defined. With strip() and split() it works well, I'll only need to remove the " ' ", but is ok. Thank you to much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.