Skip to content
Advertisement

calling list() method over array of one element raises TypeError: iteration over a 0-d array

calling list() method over pandas dataframe single row raises an error. For example,

 d = {'col1': ['a', 'b', 'a'], 'col2': ['c', 'd', 'e']}
 df = pd.DataFrame(data=d)
 df

Now, the below is fine

list(df.loc[df.col1 == 'a']['col2'].values.squeeze())

but,

list(df.loc[df.col1 == 'b']['col2'].values.squeeze())

raises:

TypeError: iteration over a 0-d array

How to address this issue?

Advertisement

Answer

You can use pd.Series.tolist() here.

df.loc[df.col1 == 'a','col2'].tolist()

df.loc[df.col1 == 'b','col2'].tolist()
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement