1

I have dataframe as below:

Name            Marks       Place               Points
John-->Hile     50          Germany-->Poland    1
Rog-->Oliver    60-->70     Australia-->US      2
Harry           80          UK                  3
Faye-->George   90          Poland              4

enter image description here

I want a result as below which finds counts of value having "-->"column wise and transpose it and result as below dataframe:

Column Count
Name   3
Marks  1
Place  1

This df is eg.This datframe is dynamic and can vary in each run like in 2nd Run we might have Name,Marks,Place or Name,Marks or anything else, So code should be dynamic which can run on any df.

2
  • Dataframe proper format is attached in the link :"Enter image description here" formatting is bit distorted. Commented Jul 7, 2020 at 6:55
  • 1
    Should it not be "3, 1, 2"? Commented Jul 7, 2020 at 6:58

1 Answer 1

1

You can select object columns and column-wise perform a count and summation:

df.select_dtypes(object).apply(lambda x: x.str.contains('-->')).sum()

Name     3
Marks    1
Place    2
dtype: int64

Another weird, but interesting method with applymap:

(df.select_dtypes(object)
   .applymap(lambda x: '-->' in x if isinstance(x, str) else False)
   .sum())

Name     3
Marks    1
Place    2
dtype: int64
Sign up to request clarification or add additional context in comments.

3 Comments

I am receiving 0 if I am running 1st option
When running 2nd Option of applymap : ""argument of type 'numpy.int64' is not iterable occurred at index Number
@Raunak you might've forgotten to assign it? As for the second problem, check my edit. Don't forget to assign it: df['result'] = df.select_dtypes(...)...

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.