tlemau
tlemau

Reputation: 13

Elementwise logical operation on character with pandas data frame

I am working with a data frame where each entry is a character from A-E representing different intensity level

For example:

data frame

df=

        1   2   3
    0   C   C   A
    1   0   D   B
    2   E   0   A

I want to threshold the data at different intensity level from A to E into a binary matrix. Thus, I want to perform an element-wise comparison.

If it's a number, it's simply: df > 0 However, when I tried with a character, df > 'A' , an error is thrown "TypeError: Could not compare ['A'] with block values"

I can of course do a 'for' loop but is there any one line, elegant solution to perform element-wise logical operation with character using data frame in pandas?

Upvotes: 1

Views: 68

Answers (2)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

I'd consider the following bit more generic approach:

In [238]: df.astype(str).applymap(ord).sub(ord('@')).replace(-16,0)
Out[238]:
   1  2  3
0  3  3  1
1  0  4  2
2  5  0  1

where:

0 - 0
1 - A
2 - B
3 - C
...

Upvotes: 1

tlemau
tlemau

Reputation: 13

Simply upgrade Pandas version to 0.21.1 and it works.

Upvotes: 0

Related Questions