Raksha
Raksha

Reputation: 1699

How to convert part of string in DataFrame cell into a number to filter by?

Here's a sample dataframe:

df = pd.DataFrame([['A0000x', 'a'],
                    ['B0010x', 'b'],
                    ['C0020x', 'c'],
                    ['D0040x', 'd']])

df.columns = ['num', 'let']

I would like to extract only the rows where the integer comprised of 3rd and 4th character in the num column is divisible by 2, for example. So I need to check if df['num'][2:4] % 2

I got this far, but can't figure out how to convert it into an integer:

df.index[df['num'].str[2:4] == '01']

Upvotes: 1

Views: 297

Answers (2)

cs95
cs95

Reputation: 402663

Use astype to convert the string column to int, then boolean index.

df['num'].str[2:4].astype(int)

0    0
1    1
2    2
3    4
Name: num, dtype: int64

df[df['num'].str[2:4].astype(int) % 2 == 0]

      num let
0  A0000x   a
2  C0020x   c
3  D0040x   d

Upvotes: 2

sentence
sentence

Reputation: 8923

import pandas as pd

df = pd.DataFrame([['A0000x', 'a'],
                    ['B0010x', 'b'],
                    ['C0020x', 'c'],
                    ['D0040x', 'd']])

df.columns = ['num', 'let']

for index, row in df.iterrows():
    if (int(row["num"][2:4]) % 2 ==0):
        print(row["num"])

Upvotes: 0

Related Questions