Home > Software engineering >  Compare nth letter in one column to a single letter in another
Compare nth letter in one column to a single letter in another

Time:06-02

I have a df as follows:

  Policy Letter             Password  Lower  Upper  Count  Lower_Minus_1  Upper_Minus_1
0    4-5      l               rllllj      4      5      4              3              4
1   4-10      s  ssskssphrlpscsxrfsr      4     10      8              3              9
2  14-18      p  ppppppppppppppppppp     14     18     19             13             17
3    1-6      z       zzlzvmqbzzclrz      1      6      6              0              5
4    4-5      j          jhjjhxhjkxj      4      5      5              3              4 

Lower_Minus_1 value is to be used as an index to search that position in the password to see if it matches the letter in column 'Letter'.

This line works:

print(df['Password'].str[3] == df['Letter'])

However, it strictly returns True\False based upon the third position for the value in 'Password' for every single row.

First five:

0       True
1      False
2       True
3       True
4       True

I don't want the third position for every row. I want the Lower_Minus_1 position for each row.

I have tried the following but both fail:

print(df['Password'].str[df['Letter']] == df['Letter'])

Returns False for every single row as proven by:

print((df['Password'].str[df['Letter']] == df['Letter']).sum())

Returns: 0

Then I tried this:

print(df.apply(lambda x: x['Password'].str[x['Lower_Minus_1']], axis=1) == df['Letter'])

This throws an error:

  File "D:/AofC/2020_day2.py", line 56, in <lambda>
    print(df.apply(lambda x: x['Password'].str[x['Lower_Minus_1']], axis=1) == df['Letter'])
AttributeError: 'str' object has no attribute 'str'

CodePudding user response:

df.apply(lambda x:x['Letter']== x['Password'][x.Lower_Minus_1], axis=1)
 
0     True
1    False
2     True
3     True
4     True
dtype: bool
  • Related