jeudi 2 novembre 2017

Efficiently search for first character of a string in a pandas dataframe

I have a pandas data frame column and I need to modify any entry of that column that starts with a 2. Right now, I'm using this which works, but is very, very slow:

for i, row in df.iterrows():
    if df['IDnumber'][i].startswith('2') == True:
       '''Do some stuff'''

I feel (read: know) there's a more efficent way to do this without using a for loop but I can't seem to find it.

Other things I've tried:

if df[df['IDnumber'].str[0]] == '2':
   '''Do some stuff'''

if df[df['IDnumber'].str.startswith('2')] == True:
    '''Do some stuff'''

Which respectively give the errors:

KeyError: "['2' '2' '2' ..., '1' '1' '1'] not in index"
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Aucun commentaire:

Enregistrer un commentaire