0

I currently have a pandas dataframe that has a column of values that are numpy arrays. I am trying to get the rows of the dataframe where the value of the column is an empty numpy array but I can't index using the pandas method. Here is an example dataframe.

data = {'Name': ['A', 'B', 'C', 'D'], 'stats': [np.array([1,1,1]), np.array([]), np.array([2,2,2]), np.array([])]}
df = pd.DataFrame(data)

I am trying to just get the rows where 'stats' is None, but when I try df[df['stats'] is None] I just get a KeyError: False. How can I filter by rows that contain an empty list?

Additionally, how can I filter by row where the numpy array is something specific? i.e. get all rows of df where df['stats'] == np.array([1, 1, 1])

Thanks

2 Answers 2

1

You can check length by Series.str.len, because it working with all Iterables:

print (df['stats'].str.len())
0    3
1    0
2    3
3    0
Name: stats, dtype: int64

And then filter, e.g. rows with len=0:

df = df[df['stats'].str.len().eq(0)]
#alternative
#df = df[df['stats'].apply(len).eq(0)]
print (df)
  Name stats
1    B    []
3    D    []

If need test specific array is possible use tuples:

df =df[ df['stats'].apply(tuple) == tuple(np.array([1, 1, 1]))]
print (df)
  Name      stats
0    A  [1, 1, 1]
Sign up to request clarification or add additional context in comments.

2 Comments

This works! Thank you so much. Just one more thing how would I check if the numpy array is something specific i.e. get all rows of df where df['stats'] == np.array([1, 1, 1])
@Anonymous Answered your second question as another answer.
1

for this question: "Additionally, how can I filter by row where the numpy array is something specific? i.e. get all rows of df where df['stats'] == np.array([1, 1, 1])"

data = {'Name': ['A', 'B', 'C', 'D'], 'stats': [np.array([1,1,1]), np.array([]), np.array([2,2,2]), np.array([])]}
df = pd.DataFrame(data)
df = df[df['stats'].apply(lambda x: np.array_equal(x, np.array([1,1,1])))]

Comments

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.