3

I have a dataframe that looks like this (but longer):

    Letter  Password
0   l       klfbblslvjclmlnqklvg
1   h       pghjchdxhnjhjd

How do I count the number of occurences of Letter in Password? Such that it is 6 for the first row and 4 for the second row.

This does not work, because count needs a regex:

df['Occurrences'] = df['Password'].str.count(df['Letter']).astype(int)

How can I do it then?

2 Answers 2

2

This case, you can use apply:

df['Occurrences'] = df.apply(lambda x: x['Password'].count(x['Letter']), axis=1)

Output:

  Letter              Password  Occurrences
0      l  klfbblslvjclmlnqklvg            6
1      h        pghjchdxhnjhjd            4
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this works great. I will surely get more use out of the apply function in the future!
1

You could do:

df['Occurrences'] = [pas.count(letter) for pas, letter in zip(df['Password'], df['Letter'])]
print(df)

Output

  Letter              Password  Occurrences
0      l  klfbblslvjclmlnqklvg            6
1      h        pghjchdxhnjhjd            4

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.