calling list() method over pandas dataframe single row raises an error. For example,
JavaScript
x
4
1
d = {'col1': ['a', 'b', 'a'], 'col2': ['c', 'd', 'e']}
2
df = pd.DataFrame(data=d)
3
df
4
Now, the below is fine
JavaScript
1
2
1
list(df.loc[df.col1 == 'a']['col2'].values.squeeze())
2
but,
JavaScript
1
2
1
list(df.loc[df.col1 == 'b']['col2'].values.squeeze())
2
raises:
JavaScript
1
2
1
TypeError: iteration over a 0-d array
2
How to address this issue?
Advertisement
Answer
You can use pd.Series.tolist()
here.
JavaScript
1
4
1
df.loc[df.col1 == 'a','col2'].tolist()
2
3
df.loc[df.col1 == 'b','col2'].tolist()
4